在Python中是否可以以以下方式迭代列表(将此代码视为伪代码)?
a = [5, 7, 11, 4, 5]
for v, w in a:
print [v, w]
它应该产生
[5, 7]
[7, 11]
[11, 4]
[4, 5]
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
for v, w in pairwise(a):
...
a
中获取循环配对感兴趣,只需执行以下操作:pairwise(a + [a[0]])
。 - 0 _itertools.pairwise
:https://docs.python.org/3/library/itertools.html#itertools.pairwise - nimble_ninja要做到这一点,您应该执行:
a = [5, 7, 11, 4, 5]
for i in range(len(a)-1):
print [a[i], a[i+1]]
几乎直接引用自在Python中循环遍历列表的成对元素:
def pairs(seq):
i = iter(seq)
prev = next(i)
for item in i:
yield prev, item
prev = item
i.next()
时会引发StopIteration
异常。 - 0 _try:
except StopIteration: return
包装起来。 - XCanG另一种方法是使用 itertools.pairwise
(Python 3.10 或更高版本):
from itertools import pairwise
temp = [-39.5, -27.5, -15.5, -3.5, 8.5, 20.5, 32.5, 44.5, 56.5, 68.5, 80.5, 92.5,104.5]
res = list(pairwise(temp))
[(-39.5, -27.5), (-27.5, -15.5), (-15.5, -3.5), (-3.5, 8.5), (8.5, 20.5), (20.5, 32.5), (32.5, 44.5), (44.5, 56.5), (56.5, 68.5), (68.5, 80.5), (80.5, 92.5), (92.5, 104.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
for n i range(len(a)):
不是更准确和符合惯用语吗? - Daniel Standage
zip(a[::2], a[1::2])
会同时遍历两个列表,每次跨度为2。 - Evgeni Sergeev