Python中迭代器的創(chuàng)建與使用詳解
Python中的迭代器是一個(gè)對象,用于迭代可迭代對象,如列表,元組,字典和集合。Python迭代器對象使用iter()方法初始化。它使用next()方法進(jìn)行迭代。
- iter():iter()方法用于迭代器的初始化。這將返回一個(gè)迭代器對象
- next():next方法返回可迭代對象的下一個(gè)值。當(dāng)我們使用for循環(huán)來遍歷任何可迭代對象時(shí),它在內(nèi)部使用iter()方法來獲取迭代器對象,迭代器對象進(jìn)一步使用next()方法進(jìn)行迭代。此方法引發(fā)StopIteration以發(fā)出迭代結(jié)束的信號(hào)。
Python iter()示例
string = "GFG" ch_iterator = iter(string) print(next(ch_iterator)) print(next(ch_iterator)) print(next(ch_iterator))
輸出
G
F
G
使用iter()和next()創(chuàng)建迭代器
下面是一個(gè)簡單的Python迭代器,它創(chuàng)建了一個(gè)從10到給定限制的迭代器類型。例如,如果限制是15,則它會(huì)打印10 11 12 13 14 15。如果限制是5,則它不打印任何內(nèi)容。
# An iterable user defined type class Test: # Constructor def __init__(self, limit): self.limit = limit # Creates iterator object # Called when iteration is initialized def __iter__(self): self.x = 10 return self # To move to next element. In Python 3, # we should replace next with __next__ def __next__(self): # Store current value ofx x = self.x # Stop iteration if limit is reached if x > self.limit: raise StopIteration # Else increment and return old value self.x = x + 1; return x # Prints numbers from 10 to 15 for i in Test(15): print(i) # Prints nothing for i in Test(5): print(i)
輸出
10
11
12
13
14
15
使用iter方法迭代內(nèi)置迭代器
在下面的迭代中,迭代狀態(tài)和迭代器變量是內(nèi)部管理的(我們看不到它),使用迭代器對象遍歷內(nèi)置的可迭代對象,如列表,元組,字典等。
# Iterating over a list print("List Iteration") l = ["geeks", "for", "geeks"] for i in l: print(i) # Iterating over a tuple (immutable) print("\nTuple Iteration") t = ("geeks", "for", "geeks") for i in t: print(i) # Iterating over a String print("\nString Iteration") s = "Geeks" for i in s : print(i) # Iterating over dictionary print("\nDictionary Iteration") d = dict() d['xyz'] = 123 d['abc'] = 345 for i in d : print("%s %d" %(i, d[i]))
輸出
List Iteration
geeks
for
geeks
Tuple Iteration
geeks
for
geeks
String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345
可迭代 vs 迭代器(Iterable vs Iterator)
Python中可迭代對象和迭代器不同。它們之間的主要區(qū)別是,Python中的可迭代對象不能保存迭代的狀態(tài),而在迭代器中,當(dāng)前迭代的狀態(tài)被保存。
注意:每個(gè)迭代器也是一個(gè)可迭代對象,但不是每個(gè)可迭代對象都是Python中的迭代器。
可迭代對象上迭代
tup = ('a', 'b', 'c', 'd', 'e') for item in tup: print(item)
輸出
a
b
c
d
e
在迭代器上迭代
tup = ('a', 'b', 'c', 'd', 'e') # creating an iterator from the tuple tup_iter = iter(tup) print("Inside loop:") # iterating on each item of the iterator object for index, item in enumerate(tup_iter): print(item) # break outside loop after iterating on 3 elements if index == 2: break # we can print the remaining items to be iterated using next() # thus, the state was saved print("Outside loop:") print(next(tup_iter)) print(next(tup_iter))
輸出
Inside loop:
a
b
c
Outside loop:
d
e
使用迭代器時(shí)出現(xiàn)StopIteration錯(cuò)誤
Python中的Iterable可以迭代多次,但當(dāng)所有項(xiàng)都已迭代時(shí),迭代器會(huì)引發(fā)StopIteration Error。
在這里,我們試圖在for循環(huán)完成后從迭代器中獲取下一個(gè)元素。由于迭代器已經(jīng)耗盡,它會(huì)引發(fā)StopIteration Exception。然而,使用一個(gè)可迭代對象,我們可以使用for循環(huán)多次迭代,或者可以使用索引獲取項(xiàng)。
iterable = (1, 2, 3, 4) iterator_obj = iter(iterable) print("Iterable loop 1:") # iterating on iterable for item in iterable: print(item, end=",") print("\nIterable Loop 2:") for item in iterable: print(item, end=",") print("\nIterating on an iterator:") # iterating on an iterator object multiple times for item in iterator_obj: print(item, end=",") print("\nIterator: Outside loop") # this line will raise StopIteration Exception # since all items are iterated in the previous for-loop print(next(iterator_obj))
輸出
Iterable loop 1:
1,2,3,4,
Iterable Loop 2:
1,2,3,4,
Iterating on an iterator:
1,2,3,4,
Iterator: Outside loop
Traceback (most recent call last):
File "scratch_1.py", line 21, in <module>
print(next(iterator_obj))
StopIteration
到此這篇關(guān)于Python中迭代器的創(chuàng)建與使用詳解的文章就介紹到這了,更多相關(guān)Python迭代器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在jupyter notebook中調(diào)用.ipynb文件方式
這篇文章主要介紹了在jupyter notebook中調(diào)用.ipynb文件方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04tensorflow查看ckpt各節(jié)點(diǎn)名稱實(shí)例
今天小編就為大家分享一篇tensorflow查看ckpt各節(jié)點(diǎn)名稱實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01一份python入門應(yīng)該看的學(xué)習(xí)資料
關(guān)于python入門你應(yīng)該看這些資料,幫助你快速入門python,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04Python的Flask路由實(shí)現(xiàn)實(shí)例代碼
這篇文章主要介紹了Python的Flask路由實(shí)現(xiàn)實(shí)例代碼,在啟動(dòng)程序時(shí),python解釋器會(huì)從上到下對代碼進(jìn)行解釋,當(dāng)遇到裝飾器時(shí),會(huì)執(zhí)行,并把函數(shù)對應(yīng)的路由以字典的形式進(jìn)行存儲(chǔ),當(dāng)請求到來時(shí),即可根據(jù)路由查找對應(yīng)要執(zhí)行的函數(shù)方法,需要的朋友可以參考下2023-08-08python pygame實(shí)現(xiàn)五子棋小游戲
這篇文章主要為大家詳細(xì)介紹了python pygame實(shí)現(xiàn)五子棋小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06