概述
迭代器是訪問集合元素的一種方式。迭代器對象從集合的第一個元素開始訪問,直到所有的元素被訪問完結束。迭代器只能往前不會后退。
延遲計算或惰性求值 (Lazy evaluation)
迭代器不要求你事先准備好整個迭代過程中所有的元素。僅僅是在迭代至某個元素時才計算該元素,而在這之前或之后,元素可以不存在或者被銷毀。這個特點使得它特別適合用於遍歷一些巨大的或是無限的集合。
可迭代對象
迭代器提供了一個統一的訪問集合的接口。只要是實現了__iter__()或__getitem__()方法的對象,就可以使用迭代器進行訪問。
序列:字符串、列表、元組
非序列:字典、文件
自定義類:用戶自定義的類實現了__iter__()或__getitem__()方法的對象
創建迭代器對象
使用內建的工廠函數iter(iterable)可以獲取迭代器對象:
語法:
iter(collection) -> iterator
iter(callable,sentinel) -> iterator
說明:
Get an iterator from an object.
In the first form, the argument must supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
實例展示:
1 使用對象內置的__iter__()方法生成迭代器 2 >>>L1 = [1,2,3,4,5,6] 3 >>>I1 = L1.__iter__() 4 >>>print I1 5 <listiterator object at 0x7fe4fd0ef550> 6 >>> I1.next() 7 1 8 >>> I1.next() 9 2 10 >>> I1.next() 11 3
1 使用內置工廠函數生成迭代器 2 >>> L1 = [1,2,3,4,5,6] 3 >>> I2 = iter(L1) 4 >>> print I2 5 <listiterator object at 0x7fe4fd0ef610> 6 >>> I2.next() 7 1 8 >>> I2.next() 9 2 10 >>> I2.next() 11 3
說明:
for循環可用於任何可迭代對象
for循環開始時,會通過迭代協議傳輸給iter()內置函數,從而能夠從迭代對象中獲得一個迭代器,返回的對象含有需要的next()方法。
