Python中迭代器的創(chuàng)建與使用詳解
Python中的迭代器是一個對象,用于迭代可迭代對象,如列表,元組,字典和集合。Python迭代器對象使用iter()方法初始化。它使用next()方法進行迭代。
- iter():iter()方法用于迭代器的初始化。這將返回一個迭代器對象
- next():next方法返回可迭代對象的下一個值。當我們使用for循環(huán)來遍歷任何可迭代對象時,它在內(nèi)部使用iter()方法來獲取迭代器對象,迭代器對象進一步使用next()方法進行迭代。此方法引發(fā)StopIteration以發(fā)出迭代結(jié)束的信號。
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)建迭代器
下面是一個簡單的Python迭代器,它創(chuàng)建了一個從10到給定限制的迭代器類型。例如,如果限制是15,則它會打印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),而在迭代器中,當前迭代的狀態(tài)被保存。
注意:每個迭代器也是一個可迭代對象,但不是每個可迭代對象都是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
使用迭代器時出現(xiàn)StopIteration錯誤
Python中的Iterable可以迭代多次,但當所有項都已迭代時,迭代器會引發(fā)StopIteration Error。
在這里,我們試圖在for循環(huán)完成后從迭代器中獲取下一個元素。由于迭代器已經(jīng)耗盡,它會引發(fā)StopIteration Exception。然而,使用一個可迭代對象,我們可以使用for循環(huán)多次迭代,或者可以使用索引獲取項。
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文件方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04