嵌套迭代使用迭代器克隆用" tee"

时间:2014-11-20 18:18:57

标签: python iterator

当我在Python

中循环遍历多个迭代器时,我注意到了直接的行为
>>> from itertools import tee
>>> X,Y = tee(range(3))
>>> [(x,y) for x in X for y in Y]
[(0, 0), (0, 1), (0, 2)]

我预计它的行为与

相同
>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

我错过了什么?我认为tee应该返回独立的迭代器..

1 个答案:

答案 0 :(得分:1)

耗尽 Y迭代器,因此zip()停止了迭代。迭代到最后,迭代器不能重复使用,就是。您必须为每个内循环生成 new 生成器。

对于您的用例,您实际上在itertools.product()使用了repeat参数:

>>> from itertools import product
>>> list(product(range(3), repeat=2))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]