假设我有一个列表
xs = [0,1,2,3]
[some_function(current, next) for current, next in zip(xs, xs[1:])]
我想迭代此列表的对(当前,下一个)。澄清zip创建列表[(0,1),(1,2),(2,3)]
问题是,如果xs是生成器而不是列表来实现这一点,我需要从中创建一个列表,这肯定不是最佳解决方案。
答案 0 :(得分:7)
您可以使用itertools.tee(iterable, n=2)
从一个迭代器创建多个独立迭代器。
my_iter, next_iter = tee(myiter)
next(nextiter)
[some_function(current, ne) for current, ne in zip(myiter, nextiter)]
答案 1 :(得分:1)
这将适用于无限迭代器等。
def pairwise(iterator):
"""Iterate over pairs of an iterator."""
last = next(iterator)
while True:
this = next(iterator)
yield last, this
last = this
答案 2 :(得分:-3)
您可以先将迭代器转换为列表(如果您确定迭代器不能无限):
xs = list(xs)
[some_function(current, next) for current, next in zip(xs, xs[1:])]