以下代码使我感到困惑:
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> iter(a)
<listiterator object at 0x7f3e9920cf50>
>>> iter(a).next()
0
>>> iter(a).next()
0
>>> iter(a).next()
0next()总是返回0。那么,iter函数是如何工作的呢?
发布于 2015-11-14 15:10:26
您每次都要创建一个新的迭代器。每一个新的迭代器从一开始就开始,它们都是独立的。
创建迭代器一次,然后遍历该实例:
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a_iter = iter(a)
>>> next(a_iter)
0
>>> next(a_iter)
1
>>> next(a_iter)
2我使用 function而不是调用iterator.next()方法;Python3将后者重命名为iterator.__next__(),但是next()函数将调用正确的‘拼写’,就像len()用于调用object.__len__一样。
https://stackoverflow.com/questions/33709805
复制相似问题