Confused with python lists: are they or are they not iterators?(对 python 列表感到困惑:它们是还是不是迭代器?)
问题描述
我正在研究 Alex Marteli 的 Python 简述 并且本书建议任何具有 next()
方法的对象都是(或至少可以用作)迭代器.它还表明,大多数迭代器是通过对名为 iter
的方法的隐式或显式调用来构建的.
I am studying Alex Marteli's Python in a Nutshell and the book suggests that any object that has a next()
method is (or at least can be used as) an iterator. It also suggests that most iterators are built by implicit or explicit calls to a method called iter
.
读完这本书后,我有一种尝试的冲动.我启动了一个 python 2.7.3 解释器并这样做了:
After reading this in the book, I felt the urge to try it. I fired up a python 2.7.3 interpreter and did this:
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for number in range(0, 10):
... print x.next()
然而结果是这样的:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
AttributeError: 'list' object has no attribute 'next'
在困惑中,我试图通过 dir(x)
研究 x 对象的结构,我注意到它有一个 __iter__
函数对象.所以我发现它可以用作迭代器,只要它支持那种类型的接口.
In confusion, I tried to study the structure of the x object via dir(x)
and I noticed that it had a __iter__
function object. So I figured out that it can be used as an iterator, so long as it supports that type of interface.
所以当我再次尝试时,这次略有不同,尝试这样做:
So when I tried again, this time slightly differently, attempting to do this:
>>> _temp_iter = next(x)
我收到了这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list object is not an iterator
但是列表怎么可能不是迭代器,因为它似乎支持此接口,并且在以下上下文中肯定可以用作一个:
But how can a list NOT be an iterator, since it appears to support this interface, and can be certainly used as one in the following context:
>>> for number in x:
... print x
有人可以帮我澄清一下吗?
推荐答案
它们是可迭代的,但它们不是迭代器.它们可以被传递给 iter()
以隐式地(例如通过 for
)或显式地为它们获取迭代器,但它们本身并不是迭代器.
They are iterable, but they are not iterators. They can be passed to iter()
to get an iterator for them either implicitly (e.g. via for
) or explicitly, but they are not iterators in and of themselves.
这篇关于对 python 列表感到困惑:它们是还是不是迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对 python 列表感到困惑:它们是还是不是迭代器?


- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 沿轴计算直方图 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12