gpt4 book ai didi

python - Python 中迭代器的静态行为

转载 作者:太空狗 更新时间:2023-10-30 01:57:46 25 4
gpt4 key购买 nike

我正在阅读 Learning Python by M.Lutz并发现了奇怪的代码块:

>>> M = map(abs, (-1, 0, 1))
>>> I1 = iter(M); I2 = iter(M)
>>> print(next(I1), next(I1), next(I1))
1 0 1
>>> next(I2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

为什么当我调用 next(I2) 时,迭代已经结束了?我不是创建了两个单独的 I1I2 实例吗?为什么它的行为类似于 static 对象的实例?

最佳答案

这与 Python 中不存在的“静态”对象无关。

iter(M) 不会创建 M 的副本。I1 和 I2 都是包装同一对象的迭代器;事实上,由于 M 已经是一个迭代器,因此调用 iter 只会返回底层对象:

>>> iter(M)
<map object at 0x1012272b0>
>>> M
<map object at 0x1012272b0>
>>> M is iter(M)
True

关于python - Python 中迭代器的静态行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36085354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com