列表为,
l = [1,2,3,4,5,6,7,8,9,0]
我如何一次迭代每两个元素?
我正在尝试这个,
for v, w in zip(l[:-1],l[1:]):
print [v, w]
获得输出就像,
[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]
[6, 7]
[7, 8]
[8, 9]
[9, 0]
预期输出
[1,2]
[3, 4]
[5, 6]
[7, 8]
[9,10]
答案 0 :(得分:9)
您可以使用iter
:
>>> seq = [1,2,3,4,5,6,7,8,9,10]
>>> it = iter(seq)
>>> for x in it:
... print (x, next(it))
...
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
您还可以使用itertools中的grouper
recipe:
>>> from itertools import izip_longest
>>> def grouper(iterable, n, fillvalue=None):
... "Collect data into fixed-length chunks or blocks"
... # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
... args = [iter(iterable)] * n
... return izip_longest(fillvalue=fillvalue, *args)
...
>>> for x, y in grouper(seq, 2):
... print (x, y)
...
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
答案 1 :(得分:8)
您可以按照自己的方式进行操作,只需在切片中添加一个步骤部分即可使两个切片跳过一个数字:
for v, w in zip(l[::2],l[1::2]): # No need to end at -1 because that's the default
print [v, w]
但我喜欢辅助生成器:
def pairwise(iterable):
i = iter(iterable)
while True:
yield i.next(), i.next()
for v, w in pairwise(l):
print v, w
答案 2 :(得分:6)
一个解决方案是
for v, w in zip(l[::2],l[1::2]):
print [v, w]
答案 3 :(得分:3)
In [180]: lst = range(1,11)
In [181]: for i in zip(*[iter(lst)]*2):
.....: print i
.....:
(1, 2)
(3, 4)
(5, 6)
(7, 8)
(9, 10)
答案 4 :(得分:3)
错误:
l = [1, 2, 3, 4, 5, 6, 7, 8]
for j in range(0, len(l), 2):
print(l[j: j + 2])
[1, 2]
[3, 4]
[5, 6]
[7, 8]
假设列表具有偶数个元素
答案 5 :(得分:2)
>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> map(None,*[iter(l)]*2)
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
>>>
答案 6 :(得分:1)
对于那些来这里要走很长一步并且不想在前面使用大量内存的人,您可以这样做。
Python 2.7:
import itertools
def step_indices(length, step):
from_indices = xrange(0, length, step)
to_indices = itertools.chain(xrange(step, length, step), [None])
for i, j in itertools.izip(from_indices, to_indices):
yield i, j
the_list = range(1234)
for i, j in step_indices(len(the_list), 100):
up_to_100_values = the_list[i:j]
Python 3:
import itertools
def step_indices(length, step):
from_indices = range(0, length, step)
to_indices = itertools.chain(range(step, length, step), [None])
for i, j in zip(from_indices, to_indices):
yield i, j
the_list = list(range(1234))
for i, j in step_indices(len(the_list), 100):
up_to_100_values = the_list[i:j]
答案 7 :(得分:0)
使用map
的另一种解决方案(语法与其他答案略有不同)。在元素数量为奇数的列表中,最后一个元素与None
配对:
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> map(None, a[::2], a[1::2])
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, None)]
您可以修改函数以返回例如列表而不是元组:
>>> map(lambda x,y:[x,y], a[::2], a[1::2])
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, None]]
>>> for e in map(lambda x,y:[x,y], a[::2], a[1::2]):
... print e
...
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
[11, None]
答案 8 :(得分:0)
我知道这是一个古老的问题,只是一种不同的方法。
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunks = [l[x:x+2] for x in range(0,len(l),2)]
print(chunks)