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結(jié)束的地方繼續(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)存占用和性能的考量。看類似下面的代碼:
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/總結(jié)
到此這篇關(guān)于Python中Yield基本用法的文章就介紹到這了,更多相關(guān)Python Yield用法內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 將properties文件的配置設(shè)置為整個Web應用的全局變量實現(xiàn)方法2. 一文秒懂idea的git插件跟翻譯插件3. docker compose idea CreateProcess error=2 系統(tǒng)找不到指定的文件的問題4. PHP設(shè)計模式之迭代器模式Iterator實例分析【對象行為型】5. 在Vue 中獲取下拉框的文本及選項值操作6. JS中的常見數(shù)組遍歷案例詳解(forEach, map, filter, sort, reduce, every)7. SpringBoot集成SSM、Dubbo、Redis、JSP的案例小結(jié)及思路講解8. python爬蟲利用代理池更換IP的方法步驟9. JS算法題解旋轉(zhuǎn)數(shù)組方法示例10. python中pandas.read_csv()函數(shù)的深入講解
