可能重复:
Iterate a list as pair (current, next) in Python
Iterating over every two elements in a list
是否可以在Python中以下列方式迭代列表(将此代码视为伪代码)?
a = [5, 7, 11, 4, 5]
for v, w in a:
print [v, w]
它应该产生
[5, 7]
[7, 11]
[11, 4]
[4, 5]
答案 0 :(得分:99)
您可以使用zip
功能:
a = [5, 7, 11, 4, 5]
for v, w in zip(a[:-1], a[1:]):
print [v, w]
答案 1 :(得分:79)
来自itertools receipes:
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
for v, w in pairwise(a):
...
答案 2 :(得分:56)
要做到这一点,你应该这样做:
a = [5, 7, 11, 4, 5]
for i in range(len(a)-1):
print [a[i], a[i+1]]
答案 3 :(得分:11)
几乎逐字逐句Iterate over pairs in a list (circular fashion) in Python:
def pairs(seq):
i = iter(seq)
prev = next(i)
for item in i:
yield prev, item
prev = item
答案 4 :(得分:5)
>>> a = [5, 7, 11, 4, 5]
>>> for n,k in enumerate(a[:-1]):
... print a[n],a[n+1]
...
5 7
7 11
11 4
4 5