当我注意到我的简单实现未产生正确的结果时,我正在为this question编写答案。在查找错误时,我注意到以下几点:
In [1]: import itertools
In [2]: gen = itertools.cycle((0,1,2))
In [3]: zip(gen, range(3))
Out[3]: [(0, 0), (1, 1), (2, 2)]
In [4]: zip(gen, range(3))
Out[4]: [(1, 0), (2, 1), (0, 2)]
无论出于何种原因,
gen
的next()
方法都称为一个额外时间。为了说明这一点,我使用了以下内容:
class loudCycle(itertools.cycle):
def next(self):
n = super(loudCycle, self).next()
print n
return n
In [6]: gen = loudCycle((0,1,2))
In [7]: zip(gen, range(3))
0
1
2
0
Out[7]: [(0, 0), (1, 1), (2, 2)]
最佳答案
发生这种情况是因为zip
对迭代器from left to right进行了评估,这意味着在执行三个步骤之后,它将在next()
上调用gen
,然后在iter(range(3))
(或类似的东西)上调用StopIteration
,然后遇到ojit_code。要解决此问题,请使用较短(有限)的iterable作为最左侧的参数:
In [8]: zip(range(3), gen)
0
1
2
Out[8]: [(0, 0), (1, 1), (2, 2)]
关于python - 为什么zip()删除生成器的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11210300/