Python淺析迭代器Iterator的使用
前言
當(dāng)我們需要對列表(list)、元組(tuple)、字典(dictionary)和集合(set)的元素進行遍歷時,其實Python內(nèi)部都是啟動迭代器來完成操作的。
迭代器(Iterator)并非Python獨有的,在C++和Java中也出現(xiàn)了此概念。迭代器可以幫助我們解決面對復(fù)雜的數(shù)據(jù)場景時,快速簡便的獲取數(shù)據(jù)。
迭代器是什么
迭代器是訪問集合的一種方式。
迭代器是一個可以記住遍歷位置的對象。
迭代器從集合的第一個元素開始訪問,直到所有的元素被訪問完才結(jié)束。
迭代器只能往往前,不能后退。
我們已經(jīng)知道,可以直接作用于for循環(huán)的數(shù)據(jù)類型有以下幾種:
一類是集合數(shù)據(jù)類型:如:list,tuple,dict,set,str等;
一類是generator,包括生成器和yield的generator function。
這些可以直接作用于for循環(huán)的對象統(tǒng)稱為可迭代對象:Iterable.
那么怎么判斷一組數(shù)據(jù)是不是Iterable對象呢?
可以使用instance()判斷一個對象是否是Iterable對象。
from collections.abc import Iterable print(isinstance([1], Iterable)) # True print(isinstance({0, 1}, Iterable)) # True print(isinstance((1, ''), Iterable)) # True print(isinstance({1: 10}, Iterable)) # True print(isinstance((i for i in range(10)), Iterable)) # True print(isinstance(10, Iterable)) # False '''
?成器不但可以作?于 for 循環(huán),還可以被 next() 函數(shù)不斷調(diào)?并返回下?個值,直到最后拋出 StopIteration 錯 誤表示?法繼續(xù)返回下?個值了。
可以被next()函數(shù)調(diào)?并不斷返回下?個值的對象稱為迭代器:Iterator。
可以使? isinstance() 判斷?個對象是 否是Iterator 對象,這里就產(chǎn)生一個疑問了,生成器都是 Iterator 對象, list 、 dict 、 str 是不是 Iterator ?為什么?。
list 、 dict 、 str 不是 Iterator ,因為Python的 Iterator 對象表示的是一個數(shù)據(jù)流,Iterator對象可以 被 next() 函數(shù)調(diào)用并不斷返回下一個數(shù)據(jù),直到?jīng)]有數(shù)據(jù)時拋出 StopIteration 錯誤。
可以把這個數(shù)據(jù)流看做 是一個有序序列,但我們卻不能提前知道序列的長度,只能不斷通過 next() 函數(shù)實現(xiàn)按需計算下一個數(shù)據(jù),所以Iterator 的計算是惰性的,只有在需要返回下一個數(shù)據(jù)時它才會計算。
Iterator 甚至可以表示一個無限大的數(shù)據(jù)流,例如全體自然數(shù)。而使用list是永遠不可能存儲全體自然數(shù)的 那我們還可以通過 isinstance() 來判斷是否是 Iterator 對象
注意 Iterator 對象和 Iterable 對象,一個是迭代器,一個是可迭代對象
from collections.abc import Iterator print(isinstance((i for i in range(10) if i % 2 == 0), Iterator)) # True print(isinstance([], Iterator)) # False print(isinstance({}, Iterator)) # False print(isinstance('abc', Iterator)) # False
但是可以將 list 、 dict 、 str 等 Iterable 變成 Iterator,這里我們可以使用 iter() 函數(shù)
代碼:
print(isinstance(iter([]), Iterator)) # True print(isinstance(iter({}), Iterator)) # True print(isinstance(iter('abc'), Iterator)) # True
所有可以作用于for循環(huán)的對象都是Iterable類型;
可以作用于next()函數(shù)的對象都是Ttreator類型,他們表示一個惰性計算序列;
集合數(shù)據(jù)類型list,dict,str等是Iterable但不是Iterator,不過可以通過iter()函數(shù)獲得一個Iterator對象。
自定義迭代器
class Myiter: def __init__(self,times): self.times = times def __iter__(self): self.n = 0 return self def __next__(self): if self.n <= self.times: result = 3 ** self.n self.n += 1 return result else: raise StopIteration data = Myiter(4) it = iter(data) # 第1次 print(next(it)) # 第2次 print(next(it)) # 第3次 print(next(it)) # 第4次 print(next(it)) # 第5次 print(next(it)) # 第6次,超出范圍觸發(fā)StopIteration print(next(it)) ... 1 3 9 27 81 Traceback (most recent call last): File "E:\workspace\uiat\cookbooks\tester.py", line 67, in <module> print(next(it)) File "E:\workspace\uiat\cookbooks\tester.py", line 51, in __next__ raise StopIteration StopIteration ...
- 創(chuàng)建的對象/類需要實現(xiàn)
__iter__()
和__next__()
兩個方法即可作為迭代器 - 迭代器中__iter__()返回迭代器本身方法
- 迭代器中__next__()方法允許進行其他操作,但是必須返回迭代器的下一項
- 為了防止迭代永遠進行下去,Python提供stopIterator語句,終止迭代
到此這篇關(guān)于Python淺析迭代器Iterator的使用的文章就介紹到這了,更多相關(guān)Python Iterator內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python入門學(xué)習(xí)關(guān)于for else的特殊特性講解
本文將介紹 Python 中的" for-else"特性,并通過簡單的示例說明如何正確使用它,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11python實現(xiàn)模擬鍵盤鼠標(biāo)重復(fù)性操作Pyautogui
這篇文章主要為大家詳細介紹了python如何利用Pyautogui模擬鍵盤鼠標(biāo)重復(fù)性操作,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11Python第三方庫xlrd/xlwt的安裝與讀寫Excel表格
最近開始學(xué)習(xí)python,想做做簡單的自動化測試,需要讀寫excel,于是就接觸到了Python的第三方庫xlrd和xlwt,下面這篇文章就給大家主要介紹了Python中第三方庫xlrd/xlwt的安裝與讀寫Excel表格的方法,需要的朋友可以參考借鑒。2017-01-01詳解tensorflow2.x版本無法調(diào)用gpu的一種解決方法
這篇文章主要介紹了詳解tensorflow2.x版本無法調(diào)用gpu的一種解決方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05python使用prettytable內(nèi)置庫美化輸出表格
這篇文章主要介紹了python使用prettytable內(nèi)置庫美化輸出表格,prettytable是pyhton內(nèi)置庫,文章圍繞主題的相關(guān)資料展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下2022-06-06