本文介绍了底层对象更改时的Python迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果底层对象在迭代期间发生变化,我想知道迭代器的一般行为是什么。

I would like to know what's the general behaviour of an iterator if the underlaying object changes during the iteration.

使用一个简单的可变列表,似乎很明显:迭代器将尝试跟随下一个元素(如果有),并发送 StopIteration 如果到达目的地。

Using a simple mutable list, it seems obvious: the iterator will try to follow on the next element if any, and send StopIteration if the end is reached.

>>> l = range(10)
>>> a = iter(l)
>>> a.next()
0
>>> a.next()
1
>>> a.next()
2
>>> l[3]='a'
>>> a.next()
'a'
>>> a.next()
4
>>> del l[5]
>>> a.next()
6
>>> a.next()
7
>>> a.next()
8
>>> a.next()
9
>>> a.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

到目前为止,这是不言自明的。我不明白的是,如果我追加一个新元素,迭代器仍将返回 StopIteration

This is self-explanatory so far. What I don't understand is, that if I append a new element, the iterator will still return StopIteration.

>>> l.append(11)
>>> a.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

如果我在到达终点前这样做:

If I do the same before reaching the end:

>>> l=[1]
>>> a=iter(l)
>>> a.next()
1
>>> l.append(2)
>>> a.next()
2

这是如何在幕后工作的,什么是更复杂的可变迭代对象的预期行为? (例如,想象一个表示图形的对象,然后可以使用遍历算法迭代。如果在迭代时添加/删除节点,应该发生什么?)

How is this working under the hood, and what is the expected behaviour of a more complex mutable iterable object? (e.g. think of an object representing a graph, which then can be iterated over, using a traversal algorithm. What is supposed to happen then if nodes are added/removed while iterating?)

推荐答案

(迭代器):

有人说要求这个是有用的,其他人说
将这个开放给个别迭代器。
注意,对于某些
迭代器实现(例如函数包装迭代器),这可能需要额外的状态位。

Some say that it would be useful to require this, others say that it is useful to leave this open to individual iterators. Note that this may require an additional state bit for some iterator implementations (e.g. function-wrapping iterators).

分辨率:一次引发StopIteration,调用it.next()
继续引发StopIteration

注意:这实际上并没有在Python 2.2中实现;有很多种情况,其中迭代器的next()方法可以在一次调用时提高
StopIteration但在下一次调用时不会提高
。这是在Python 2.3中补救的

Note: this was in fact not implemented in Python 2.2; there are many cases where an iterator's next() method can raise StopIteration on one call but not on the next. This has been remedied in Python 2.3.

这篇关于底层对象更改时的Python迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 14:13