问题描述
以下代码使我感到困惑:
The following code confuses me:
>>> 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
函数如何工作?
next()
is always returning 0. So, how does the iter
function work?
推荐答案
您每次都创建一个 new 迭代器.每个新的迭代器都从头开始,它们都是独立的.
You are creating a new iterator each time. Each new iterator starts at the beginning, they are all independent.
创建一次迭代器,然后对该一个实例进行迭代:
Create the iterator once, then iterate over that one instance:
>>> 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()
函数,而不是调用了iterator.next()
方法; Python 3将后者重命名为iterator.__next__()
,但是next()
函数将调用正确的拼写",就像使用len()
调用object.__len__
一样.
I used the next()
function rather than calling the iterator.next()
method; Python 3 renames the latter to iterator.__next__()
but the next()
function will call the right 'spelling', just like len()
is used to call object.__len__
.
这篇关于Python iter()函数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!