Iterate through adjacent pairs of items in a Python list [duplicate]
Is it possible to iterate a list in the following way in Python (treat this code as pseudocode)开发者_Python百科?
a = [5, 7, 11, 4, 5]
for v, w in a:
print [v, w]
And it should produce
[5, 7]
[7, 11]
[11, 4]
[4, 5]
You can zip
the list with itself sans the first element:
a = [5, 7, 11, 4, 5]
for previous, current in zip(a, a[1:]):
print(previous, current)
This works even if your list has no elements or only 1 element (in which case zip
returns an empty iterable and the code in the for
loop never executes). It doesn't work on generators, only sequences (tuple
, list
, str
, etc).
From the itertools
recipes:
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):
...
To do that you should do:
a = [5, 7, 11, 4, 5]
for i in range(len(a)-1):
print [a[i], a[i+1]]
Nearly verbatim from 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
>>> 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
精彩评论