Python iter()函数如何工作?

时间:2015-11-14 15:09:48

标签: python iterator

以下代码让我感到困惑:

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> zip(*([iter(a)]*2))
[(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()
0

next()始终返回0.那么,iter函数如何工作?

1 个答案:

答案 0 :(得分:8)

您每次都在创建 new 迭代器。每个新的迭代器都从一开始就开始,它们都是独立的。

创建一次迭代器,然后遍历那个实例:

>>> 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

我使用next() function而不是调用iterator.next()方法; Python 3将后者重命名为iterator.__next__(),但next()函数会调用正确的拼写&#39;,就像使用len()来调用object.__len__一样。< / p>