Python中Yield的基本用法
帶有yield的函數(shù)在Python中被稱之為generator(生成器),也就是說,當你調(diào)用這個函數(shù)的時候,函數(shù)內(nèi)部的代碼并不立即執(zhí)行 ,這個函數(shù)只是返回一個生成器(Generator Iterator)。
def generator(): for i in range(10) : yield i*igen = generator()print(gen)<generator object generator at 0x7ffaad115aa0>
1. 使用next方法迭代生成器
generator函數(shù)怎么調(diào)用呢?答案是next函數(shù)。
print('first iteration:')print(next(gen))print('second iteration:')print(next(gen))print('third iteration:')print(next(gen))print('fourth iteration:')print(next(gen))
程序輸出:
first iteration: 0 second iteration: 1 three iteration: 4 four iteration: 9
在函數(shù)第一次調(diào)用next(gen)函數(shù)時,generator函數(shù)從開始執(zhí)行到y(tǒng)ield,并返回yield之后的值。
在函數(shù)第二次調(diào)用next(gen)函數(shù)時,generator函數(shù)從上一次yield結束的地方繼續(xù)運行,直至下一次執(zhí)行到y(tǒng)ield的地方,并返回yield之后的值。依次類推。
2. 使用send()方法與生成器函數(shù)通信
def generator(): x = 1 while True: y = (yield x) x += ygen = generator() print('first iteration:')print(next(gen))print('send iteration:')print(gen.send(10))
代碼輸出:
first iteration: 1 send iteration: 11
生成器(generator)函數(shù)用yield表達式將處理好的x發(fā)送給生成器(Generator)的調(diào)用者;然后生成器(generator)的調(diào)用者可以通過send函數(shù),將外部信息替換生成器內(nèi)部yield表達式的返回值,并賦值給y,并參與后續(xù)的迭代流程。
3. Yield的好處
Python之所以要提供這樣的解決方案,主要是內(nèi)存占用和性能的考量??搭愃葡旅娴拇a:
for i in range(10000): ...
上述代碼的問題在于,range(10000)生成的可迭代的對象都在內(nèi)存中,如果數(shù)據(jù)量很大比較耗費內(nèi)存。
而使用yield定義的生成器(Generator)可以很好的解決這一問題。
參考材料
https://pyzh.readthedocs.io/en/latest/the-python-yield-keyword-explained.html https://liam.page/2017/06/30/understanding-yield-in-python/總結
到此這篇關于Python中Yield基本用法的文章就介紹到這了,更多相關Python Yield用法內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章: