[英]Static behavior of iterators in Python
I am reading Learning Python by M.Lutz and found bizarre block of code: 我正在阅读M.Lutz的学习Python ,发现奇怪的代码块:
>>> 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
Why when I call next(I2)
it happens that iteration is already over? 为什么当我调用next(I2)
时,迭代已经结束? Didn't I create two separate instances of I1
and I2
. 我没有创建两个单独的I1
和I2
实例。 Why does it behave like an instances of a static
object? 为什么它的行为类似于static
对象的实例?
This has nothing to do with "static" objects, which don't exist in Python. 这与“静态”对象无关,而Python中不存在这些对象。
iter(M)
does not create a copy of M. Both I1 and I2 are iterators wrapping the same object; iter(M)
不会创建iter(M)
的副本.I1和I2都是包装同一对象的迭代器; in fact, since M
is already an iterator, calling iter
on it just returns the underlying object: 事实上,由于M
已经是一个迭代器,因此在它上面调用iter
只返回底层对象:
>>> iter(M)
<map object at 0x1012272b0>
>>> M
<map object at 0x1012272b0>
>>> M is iter(M)
True
This happens because in Python 3.X, map
objects can be iterated over only once. 发生这种情况是因为在Python 3.X中, map
对象只能迭代一次。 Pointing multiple iterators at it won't reset it to its starting state. 在它上面指向多个迭代器不会将其重置为其启动状态。
Compare to map
's behavior in 2.7. 比较2.7中map
的行为。 It returns a list, so it can be iterated over multiple times. 它返回一个列表,因此可以多次迭代。
>>> M = map(abs, (-1, 0, 1))
>>> I1 = iter(M); I2 = iter(M)
>>> print(next(I1), next(I1), next(I1))
(1, 0, 1)
>>> next(I2)
1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.