3 回答

慕桂英4014372
TA贡献1871条经验 获得超13个赞
您可以zip在这里使用:
>>> lis = ['a', 'b', 'c', 'd', 'e']
>>> for x,y in zip(lis,lis[1:]):
... print x,y
...
a b
b c
c d
d e

临摹微笑
TA贡献1982条经验 获得超2个赞
itertools成对配方适用于任何迭代
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)
path = ['a', 'b', 'c', 'd', 'e']
>>> for x, y in pairwise(path):
print x, y
a b
b c
c d
d e
>>> list(pairwise(path))
[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]

富国沪深
TA贡献1790条经验 获得超9个赞
实现此目的的最佳方法不是通过列表理解,而是zip()
:
advanced = iter(path)next(advanced, None)for item, next_item in zip(path, advanced): ...
我们在这些值上生成一个迭代器,将其前进一个值,因此我们从第二个值开始,然后使用循环遍历原始列表和高级列表zip()
。
添加回答
举报
0/150
提交
取消