ITPub博客

首页 > IT职业 > IT职场 > python中yield from怎么用?

python中yield from怎么用?

IT职场 作者:seiya 时间:2021-09-11 10:02:06 0 删除 编辑

 

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

yield from本质:

for item in iterable: yield item的缩写版

代码示例:

def g(x):
    yield from range(x , 0, -1)
    yield from range(x)
print(list(g(5)))

利用yield from语句向生成器(协程)传送数据:

def writer():
    while True:
        w = (yield) 
        print('>>', w)
def writer_wrapper(coro1):
coro1.send(None) 
    while True:
        try:
            x = (yield) 
            coro1.send(x) 
        except StopIteration:
            pass
def writer_wrapper(coro2):
yield from coro2

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4586/viewspace-2831122/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-13

  • 博文量
    81
  • 访问量
    677