Python3迭代器和生成器
迭代器
迭代是Python最強大的功能之一,是訪問元素集合的一種方法。
迭代器是一個可以記住遍歷的位置的對象。
迭代器對象從集合的第一個元素開始訪問,直到所有的元素被訪問完結(jié)束,迭代器只能向前不會后退。
迭代器有兩個基本方法,iter()和next()。
字符串,列表,或元組對象都可以用于創(chuàng)建迭代器。
?
?
迭代器對象可以使用常規(guī)語句for進行遍歷:
?
?
?
使用next()函數(shù):
#next.py import syslist = [1,2,3,4] it = iter(list)while True:try:print(next(it))except StopIteration:sys.exit()運行結(jié)果:
robot@ubuntu:~/wangqinghe/python/20190827$ python3.5 next.py
1
2
3
4
?
創(chuàng)建一個迭代器:
把一個類作為一個迭代器使用需要在類中實現(xiàn)兩個方法__iter__()與__next__().
類都是由一個構(gòu)造函數(shù),Python的構(gòu)造函數(shù)為__init__(),它會在對象初始化的時候執(zhí)行。
__iter__方法返回一個特殊的迭代器對象,這個迭代器對象實現(xiàn)了__next__()方法通過StopIteration異常標識迭代的完成。
__next__()方法會返回下一個迭代器對象。
?
#iter.py class MyNumbers:def __iter__(self):self.a = 1return selfdef __next__(self):x = self.aself.a += 1return xmyclass = MyNumbers() myiter = iter(myclass)print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter))運行結(jié)果:
robot@ubuntu:~/wangqinghe/python/20190827$ python3.5 iter.py
1
2
3
4
5
6
?
StopIteration
StopIteration異常用于標識迭代的完成,防止出現(xiàn)無限循環(huán)的情況,在__next__方法種我們可以設置在完成指定循環(huán)次數(shù)后觸發(fā)StopIteration異常來結(jié)束迭代。
?
在20次迭代后停止執(zhí)行:
#stop.py class MyNumbers:def __iter__(self):self.a = 1return selfdef __next__(self):if self.a <= 20:x = self.aself.a += 1return xelse:raise StopIterationmyclass = MyNumbers() myiter = iter(myclass)for x in myiter:print(x)運行結(jié)果:
robot@ubuntu:~/wangqinghe/python/20190827$ python3.5 stop.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
?
生成器:
在Python中,使用了yield的函數(shù)被稱為生成器(generator)。
跟普通函數(shù)不同,生成器是一個返回迭代器的函數(shù),只能用于迭代操作,更簡單點理解生成器就是一個迭代器。
在調(diào)用生成器運行過程中,每次遇到y(tǒng)ield時函數(shù)會暫停并保持當前所有運行信息,返回yield的值,并在下一次執(zhí)行next()方法時從當前位置繼續(xù)運行。
調(diào)用一個生成器函數(shù),返回的是一個迭代器對象。
#yield.py import sysdef fibonacci(n):a,b,counter = 0,1,0while True:if(counter > n):return yield aa,b = b,a+bcounter += 1 f = fibonacci(10)while True:try:print(next(f),end=" ")except StopIteration:sys.exit()運行結(jié)果:
robot@ubuntu:~/wangqinghe/python/20190827$ python3 yield.py
0 1 1 2 3 5 8 13 21 34 55
?
什么時候需要用到y(tǒng)ield
一個函數(shù)f,返回一個list,這個list是動態(tài)計算出來的,并且這個list會很大,這個時候我們希望每次調(diào)用這個函數(shù)并使用迭代器進行循環(huán)的時候,一個一個的得到每個list的值,而不是直接得到一個list來節(jié)省內(nèi)存,這個時候yield就很有用。
?
轉(zhuǎn)載于:https://www.cnblogs.com/wanghao-boke/p/11419965.html
總結(jié)
以上是生活随笔為你收集整理的Python3迭代器和生成器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一般网页中记住密码是怎么实现的,这个安全
- 下一篇: 成都欢乐谷宠物能进吗