Python iter()函数如何工作? [英] How does the Python iter() function work?

查看:97
本文介绍了Python iter()函数如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使我感到困惑:

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()函数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆