当前位置: 首页 > 图灵资讯 > 行业资讯> python中yield from怎么用?

python中yield from怎么用?

来源:图灵python
时间: 2024-09-18 17:32:51

本教程的操作环境:windows7系统,Python 3.9.1,DELL G3电脑。

yield from本质:

for item in iterable: yield 缩写版的item

代码示例:

defg(x):
yieldfromrange(x,0,-1)
yieldfromrange(x)
print(list(g(5)))

利用yield 将数据传输到生成器(协程)

defwriter():
whileTrue:
w=(yield)
print('>>',w)
defwriter_wrapper(coro1):
coro1.send(None)
whileTrue:
try:
x=(yield)
coro1.send(x)
exceptStopIteration:
pass
defwriter_wrapper(coro):
yieldfromcoro