python迭代器,python代器
可直接作用於for迴圈的對象叫做可迭代對象(iterable);可被next()函數調用並不斷返回下一個值的對象稱為迭代器(iterator);所有的可迭代對象均可以通過內建函數iter()來轉變為迭代器。在使用for迴圈的時候,程式就會自動調用即將處理的對象的迭代器對象,然後使用它的next()方法,直到檢測一個stoplteration異常。
>>> l = [4,5,6,7,8,9,0] #這是一個列表
>>> i = iter(l) #可迭代對象轉換為迭代器;
>>> next(i)
4
>>> next(i)
5
>>> next(i)
6
>>> next(i)
7
>>> next(i)
8
>>> next(i)
9
>>> next(i)
0
>>> next(i)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
因為列表中麼有超過0的數字,所以當範圍超過的話,就會返回一個StopIteration異常。
在生產環境中如何判斷呢
>>> L = [4,5,6]
>>> I = L.__iter__()
>>> L.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__next__'
>>> I.__next__()
4
>>> from collections import Iterator, Iterable
>>> isinstance(L, Iterable)
True
>>> isinstance(L, Iterator)
False
>>> isinstance(I, Iterable)
True
>>> isinstance(I, Iterator)
True
>>> [x**2 for x in I]
[25, 36]