Python中Yield的基本用法
作者:半杯茶的小酒杯 时间:2021-08-30 15:34:55
带有yield的函数在Python中被称之为generator(生成器),也就是说,当你调用这个函数的时候,函数内部的代码并不立即执行 ,这个函数只是返回一个生成器(Generator Iterator)。
def generator():
for i in range(10) :
yield i*i
gen = generator()
print(gen)
<generator object generator at 0x7ffaad115aa0>
1. 使用next方法迭代生成器
generator函数怎么调用呢?答案是next函数。
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
在函数第一次调用next(gen)函数时,generator函数从开始执行到yield,并返回yield之后的值。
在函数第二次调用next(gen)函数时,generator函数从上一次yield结束的地方继续运行,直至下一次执行到yield的地方,并返回yield之后的值。依次类推。
2. 使用send()方法与生成器函数通信
def generator():
x = 1
while True:
y = (yield x)
x += y
gen = generator()
print("first iteration:")
print(next(gen))
print("send iteration:")
print(gen.send(10))
代码输出:
first iteration:
1
send iteration:
11
生成器(generator)函数用yield表达式将处理好的x发送给生成器(Generator)的调用者;然后生成器(generator)的调用者可以通过send函数,将外部信息替换生成器内部yield表达式的返回值,并赋值给y,并参与后续的迭代流程。
3. Yield的好处
Python之所以要提供这样的解决方案,主要是内存占用和性能的考量。看类似下面的代码:
for i in range(10000):
...
上述代码的问题在于,range(10000)生成的可迭代的对象都在内存中,如果数据量很大比较耗费内存。
而使用yield定义的生成器(Generator)可以很好的解决这一问题。
参考材料
https://pyzh.readthedocs.io/en/latest/the-python-yield-keyword-explained.html
https://liam.page/2017/06/30/understanding-yield-in-python/
来源:http://www.banbeichadexiaojiubei.com/index.php/2020/10/17/python%e4%b8%ad%e7%9a%84yield%e7%94%a8%e6%b3%95/
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Go项目实现优雅关机与平滑重启功能
python 使用事件对象asyncio.Event来同步协程的操作
从Web查询数据库之PHP与MySQL篇
js鼠标动画特效
![](https://img.aspxhome.com/file/UploadPic/20079/26/2007926183743348s.gif)
详细讲解SQL Server数据库的文件恢复技术
MSSQL中部分字段重复数据的删除方法
ASP伪造REFERER方法
设计地址栏透明icon图标方法
![](https://img.aspxhome.com/file/UploadPic/200810/25/20081025172534705s.jpg)
asp连接access数据库表代码实例
Python数据正态性检验实现过程
![](https://img.aspxhome.com/file/2023/3/78703_0s.png)
python实现邮箱发送信息
Golang二维数组的使用方式
JavaScript 实现模态对话框 源代码大全
几个优化WordPress中JavaScript加载体验的插件介绍
ASP使用xmlhttp调用WEBSERVICE文档
从SNS看社会化界面设计(一)
![](https://img.aspxhome.com/file/UploadPic/20092/23/1-73s.jpg)
python数据可视化Pyecharts库sankey修改桑葚图颜色
![](https://img.aspxhome.com/file/2023/5/76765_0s.jpg)
书写高效的CSS - 漫谈CSS的渲染效率
CSS在Internet Explorer 6, 7 和8中的差别
![](https://img.aspxhome.com/file/UploadPic/up/2009102618430043.gif)
浅谈图表参数化设计
![](https://img.aspxhome.com/file/UploadPic/20108/29/01-56s.jpg)