Python itertools.tee 困惑

Python itertools.tee 困惑

https://docs.python.org/3/lib...)-,Return%20n%20independent%20iterators%20from%20a%20single%20iterable.,-The%20following%20Python

官方文档说 functools.tee 会生成独立的多个迭代器,但是对生成的其中一个迭代器(g1)进行操作似乎会影响到另一个迭代器(g2)的行为。
代码如下,注释部分取消后,输出为
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
而不取消注释的输出为:
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21]

from itertools import tee

def func():

g = (x for x in range(3, 100, 2))

while True:

n = next(g)

yield n

g = filter(lambda x: x % n > 0, g)

g1, g2 = tee(g, 2)

# for i in range(10):

# next(g1)

g = g2

g = func()

print([next(g) for i in range(10)])


回答:

Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed.

这个程序里生成了很多 iter ,所有得 iter 最终都是基于 (x for x in range(3,100,2)) 的。每一个都有可能引起它的变化。于是所有都有可能会互相影响。


这个写得太乱了 ...

以上是 Python itertools.tee 困惑 的全部内容, 来源链接: utcz.com/p/938396.html

回到顶部