簡體   English   中英

與python列表混淆:它們還是不是迭代器?

[英]Confused with python lists: are they or are they not iterators?

在一個Nutshell中研究Alex Marteli的Python,書中建議任何具有next()方法的對象(或者至少可以用作迭代器) 它還表明大多數迭代器是通過對名為iter的方法的隱式或顯式調用構建的。

在書中讀到這篇文章后,我感受到了嘗試它的沖動。 我啟動了一個python 2.7.3解釋器,並做到了這一點:

>>> 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__函數對象。 所以我發現它可以用作迭代器,只要它支持那種類型的接口。

所以當我再次嘗試時,這一次略有不同,嘗試這樣做:

>>> _temp_iter = next(x)

我收到了這個錯誤:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list object is not an iterator

但是如何列表不是迭代器,因為它似乎支持這個接口,並且當然可以在以下上下文中用作一個:

>>> for number in x:
...     print x

有人可以幫助我在腦海中澄清這一點嗎?

它們是可迭代的 ,但它們不是迭代器 它們可以傳遞給iter()以隱式(例如,通過for )或顯式地為它們獲取迭代器,但它們本身並不是迭代器。

您需要首先使用iter()將列表轉換為迭代器:

In [7]: x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [8]: it=iter(x)

In [9]: for i in range(10):
    it.next()
   ....:     
   ....:     
Out[10]: 0
Out[10]: 1
Out[10]: 2
Out[10]: 3
Out[10]: 4
Out[10]: 5
Out[10]: 6
Out[10]: 7
Out[10]: 8
Out[10]: 9

In [12]: 'next' in dir(it)
Out[12]: True

In [13]: 'next' in dir(x)
Out[13]: False

檢查對象是否是迭代器:

In [17]: isinstance(x,collections.Iterator)
Out[17]: False

In [18]: isinstance(x,collections.Iterable)
Out[18]: True

In [19]: isinstance(it,collections.Iterable) 
Out[19]: True

In [20]: isinstance(it,collections.Iterator)
Out[20]: True

以防您對iterables和迭代器之間的區別感到困惑。 迭代器是表示數據流的對象。 它實現了迭代器協議:

  • __iter__方法
  • next方法

重復調用迭代器的next()方法返回流中的連續項。 當沒有更多數據可用時,迭代器對象就會耗盡,並且對next()方法的任何進一步調用都會再次引發StopIteration。

另一方面,可迭代對象實現__iter__方法,該方法在調用時返回迭代器,該迭代器允許對其數據進行多次傳遞。 可重復使用的對象是可重用的,一旦耗盡,它們就可以重復迭代。 可以使用iter函數將它們轉換為迭代器。

所以,如果你有一個列表(可迭代),你可以這樣做:

>>> l = [1,2,3,4]
>>> for i in l:
...     print i,
1 2 3 4
>>> for i in l:
...     print i,
 1 2 3 4

如果將列表轉換為迭代器:

>>> il = l.__iter__()  # equivalent to iter(l)
>>> for i in il:
...     print i,
 1 2 3 4
>>> for i in il:
...     print i,
>>> 

List不是迭代器,但是list包含一個迭代器對象__iter__所以當你嘗試在任何列表中使用for循環時,for循環調用__iter__方法並獲取迭代器對象然后它使用list的next()方法。

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
it = x.__iter__()

現在it包含x迭代器對象,您可以將其用作it.next()直到拋出StopIteration異常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM