07-07 生成器

目錄

  • 一 生成器與yield

  • 二 yield表達(dá)式應(yīng)用

  • 三 三元表達(dá)式、列表生成式、生成器表達(dá)式

    • 3.1 三元表達(dá)式

    • 3.2 列表生成式

    • 3.3 生成器表達(dá)式

  • 四 視頻鏈接

一 生成器與yield

若函數(shù)體包含yield關(guān)鍵字,再調(diào)用函數(shù),并不會執(zhí)行函數(shù)體代碼,得到的返回值即生成器對象

>>> def my_range(start,stop,step=1):
...     print('start...')
...     while start < stop:
...         yield start
...         start+=step
...     print('end...')
... 
>>> g=my_range(0,3)
>>> g
<generator object my_range at 0x104105678>

生成器內(nèi)置有__iter__和__next__方法,所以生成器本身就是一個迭代器

>>> g.__iter__
<method-wrapper '__iter__' of generator object at 0x1037d2af0>
>>> g.__next__
<method-wrapper '__next__' of generator object at 0x1037d2af0>

因而我們可以用next(生成器)觸發(fā)生成器所對應(yīng)函數(shù)的執(zhí)行,

>>> next(g) # 觸發(fā)函數(shù)執(zhí)行直到遇到y(tǒng)ield則停止,將yield后的值返回,并在當(dāng)前位置掛起函數(shù)
start...
0
>>> next(g) # 再次調(diào)用next(g),函數(shù)從上次暫停的位置繼續(xù)執(zhí)行,直到重新遇到y(tǒng)ield...
1
>>> next(g) # 周而復(fù)始...
2
>>> next(g) # 觸發(fā)函數(shù)執(zhí)行沒有遇到y(tǒng)ield則無值返回,即取值完畢拋出異常結(jié)束迭代
end...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

既然生成器對象屬于迭代器,那么必然可以使用for循環(huán)迭代,如下:

>>> for i in countdown(3):
...     print(i)
... 
countdown start
3
2
1
Done!

有了yield關(guān)鍵字,我們就有了一種自定義迭代器的實現(xiàn)方式。yield可以用于返回值,但不同于return,函數(shù)一旦遇到return就結(jié)束了,而yield可以保存函數(shù)的運行狀態(tài)掛起函數(shù),用來返回多次值

二 yield表達(dá)式應(yīng)用

在函數(shù)內(nèi)可以采用表達(dá)式形式的yield

>>> def eater():
...     print('Ready to eat')
...     while True:
...         food=yield
...         print('get the food: %s, and start to eat' %food)
... 

可以拿到函數(shù)的生成器對象持續(xù)為函數(shù)體send值,如下

>>> g=eater() # 得到生成器對象
>>> g
<generator object eater at 0x101b6e2b0>
>>> next(e) # 需要事先”初始化”一次,讓函數(shù)掛起在food=yield,等待調(diào)用g.send()方法為其傳值
Ready to eat
>>> g.send('包子')
get the food: 包子, and start to eat
>>> g.send('雞腿')
get the food: 雞腿, and start to eat

針對表達(dá)式形式的yield,生成器對象必須事先被初始化一次,讓函數(shù)掛起在food=yield的位置,等待調(diào)用g.send()方法為函數(shù)體傳值,g.send(None)等同于next(g)。

? 我們可以編寫裝飾器來完成為所有表達(dá)式形式y(tǒng)ield對應(yīng)生成器的初始化操作,如下

def init(func):
    def wrapper(*args,**kwargs):
        g=func(*args,**kwargs)
        next(g)
        return g
    return wrapper

@init
def eater():
    print('Ready to eat')
    while True:
        food=yield
        print('get the food: %s, and start to eat' %food)

表達(dá)式形式的yield也可以用于返回多次值,即變量名=yield 值的形式,如下

>>> def eater():
...     print('Ready to eat')
...     food_list=[]
...     while True:
...         food=yield food_list
...         food_list.append(food)
... 
>>> e=eater()
>>> next(e)
Ready to eat
[]
>>> e.send('蒸羊羔')
['蒸羊羔']
>>> e.send('蒸熊掌')
['蒸羊羔', '蒸熊掌']
>>> e.send('蒸鹿尾兒')
['蒸羊羔', '蒸熊掌', '蒸鹿尾兒']

三 三元表達(dá)式、列表生成式、生成器表達(dá)式

3.1 三元表達(dá)式

三元表達(dá)式是python為我們提供的一種簡化代碼的解決方案,語法如下

res = 條件成立時返回的值 if 條件 else 條件不成立時返回的值

針對下述場景

def max2(x,y):
    if x > y:
        return x
    else:
        return y
    
res = max2(1,2)

用三元表達(dá)式可以一行解決

x=1
y=2
res = x if x > y else y # 三元表達(dá)式

3.2 列表生成式

列表生成式是python為我們提供的一種簡化代碼的解決方案,用來快速生成列表,語法如下

[expression for item1 in iterable1 if condition1
for item2 in iterable2 if condition2
...
for itemN in iterableN if conditionN
]

#類似于
res=[]
for item1 in iterable1:
    if condition1:
        for item2 in iterable2:
            if condition2
                ...
                for itemN in iterableN:
                    if conditionN:
                        res.append(expression)

針對下述場景

egg_list=[]
for i in range(10):
    egg_list.append('雞蛋%s' %i)

用列表生成式可以一行解決

egg_list=['雞蛋%s' %i for i in range(10)]

3.3 生成器表達(dá)式

創(chuàng)建一個生成器對象有兩種方式,一種是調(diào)用帶yield關(guān)鍵字的函數(shù),另一種就是生成器表達(dá)式,與列表生成式的語法格式相同,只需要將[]換成(),即:

(expression for item in iterable if condition)

對比列表生成式返回的是一個列表,生成器表達(dá)式返回的是一個生成器對象

>>> [x*x for x in range(3)]
[0, 1, 4]
>>> g=(x*x for x in range(3))
>>> g
<generator object <genexpr> at 0x101be0ba0>

對比列表生成式,生成器表達(dá)式的優(yōu)點自然是節(jié)省內(nèi)存(一次只產(chǎn)生一個值在內(nèi)存中)

>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g) #拋出異常StopIteration

如果我們要讀取一個大文件的字節(jié)數(shù),應(yīng)該基于生成器表達(dá)式的方式完成

with open('db.txt','rb') as f:
    nums=(len(line) for line in f)
    total_size=sum(nums) # 依次執(zhí)行next(nums),然后累加到一起得到結(jié)果=

加qq群830644110獲取更多高級文章&項目源代碼

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容