关于python itertools.tee的混乱 - itertools产生的迭代器会互相影响吗?
Python版本:3.9.7
我在 itertools.tee “ rel =“ nofollow noreferrer”>官方文档。
从单个迭代中返回n个独立的迭代器。
但是我发现由 itertools.tee
生成的迭代器似乎会影响他人。这是我的代码:
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
gg = func()
print([next(gg) for i in range(10)])
# Output:
# [3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
但是,如果我不输入第12和13行
,输出会像这样更改:
[3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
谁能告诉我原因?我很困惑。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由
itertools.tee返回的迭代器
是独立的,因为它们可以在不影响数据流中彼此的位置的情况下进行进步。从您似乎预期的意义上讲,它们并不是完全独立的。不可能使它们独立于。您的代码有一个错误。这:
并不意味着您认为它的作用。
n
懒洋洋地查找。n
更改的值后,过滤器将使用错误的值。当您输入注释的循环时,该循环立即将Tee迭代器之一升级10次,这将使基础过滤器迭代器10次进步以产生值。这些值是用正确的
n
计算的,因为尚未重新分配n
,并且该值存储在TEE的基础存储器中,以供其他Tee迭代器使用。这足以隐藏懒惰n
错误。随着循环的评论,每个滤镜迭代器都懒惰地进行了高级。错误的
n
几乎每次都使用。The iterators returned by
itertools.tee
are independent in the sense that they can be advanced without affecting each other's positions in the data stream. They are not completely independent in the sense you seem to have expected. It would be impossible to make them that independent.Your code has a bug. This:
doesn't mean what you think it does.
n
is looked up lazily. As soon as the value ofn
changes, the filter will be using the wrong value.When you uncomment the commented-out loop, that loop immediately advances one of the tee iterators 10 times, which advances the underlying filter iterator 10 times to produce values. These values are computed with the correct
n
, sincen
hasn't been reassigned yet, and the values are stored in the tee's underlying storage for the other tee iterator to use. This is enough to hide the lazyn
bug.With the loop commented out, each filter iterator is advanced lazily. The wrong
n
is used almost every time.