問題描述
我正在研究 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 列表感到困惑:它們是還是不是迭代器?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!