2016-05-23 54 views

回答

3

列表是迭代。你可以通過調用iter(iterable)爲它們生成一個迭代器。

沒有包含迭代器和排除生成器的特殊術語。

準確定義見Python glossaryiterator,iterablegenerator

例如,發生器條目包括:

其返回迭代的函數。

這是很常見的使用生成函數來實現迭代器的迭代,通過實施object.__iter__

class SomeContainer(object): 
    def __iter__(self): 
     for elem in self._datastructure: 
      if elem.visible: 
       yield elem.value 

所以SomeContainer實例是迭代(就像名單),iter(iterable)產生一個迭代器,其中恰好是一個發生器對象

+0

會發電機對象也是一個迭代的話,因爲它有一個'__iter__'功能,併產生一個迭代還是我犯了這個錯誤 – Xiphias

+0

@Xiphias:??每一個迭代器是迭代的,是的 –

2

列表不是迭代器。列表是可疑錯誤,當你調用iter(somelist)它會產生一個迭代器。什麼樣的迭代器產生取決於所討論的Iterable,列表中的一個是相當充分的名稱列表。

任何生成器都是迭代器。
任何迭代器是一個可迭代(嘗試iter(iter(somelist))
沒有任何可迭代(列表,例如)是一個迭代器,但是當你調用iter(someiterable)someiterable.__iter__()可迭代返回一個Iterator

編輯:這裏是一個短( Python 3中)例如:

>>> import collections 
>>> import random 
>>> 
>>> class MyIterable: 
...  def __iter__(self): 
...   return MyIterator() 
>>> 
>>> class MyIterator: 
...  def __next__(self): 
...   return random.randint(-10, 10) 
...  def __iter__(self): 
...   return self 
... 
>>> mable = MyIterable() 
>>> mitor = iter(mable) 
>>> isinstance(mable, collections.Iterable) 
True 
>>> isinstance(mable, collections.Iterator) 
False 
>>> isinstance(mitor, collections.Iterable) 
True 
>>> isinstance(mitor, collections.Iterator) 
True 
>>> next(mitor) 
-7 
>>> next(mitor) 
-3 
>>> next(mitor) 
-3 
>>> next(mitor) 
7 
>>> next(mable) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'MyIterable' object is not an iterator 
+0

我明白了,沒有任何iterable是迭代器,因爲生成器是可迭代的,但不是迭代器? – Xiphias

+1

@Xiphias不完全。生成器是一種特殊的迭代器,所以任何生成器都是迭代器。沒有任何Iterable是一個迭代器,因爲Iterables和迭代器是兩回事。 Iterables能夠生成迭代器。迭代器是具有'__iter__'和'__next__'方法的對象。所有迭代器都是Iterables,因爲它們可以生成迭代器(按照慣例,當在Iterator上調用iter時,它們會自己返回)。 – timgeb