yield
yield不仅可以返回值,也可以接收值
# yield返回值, 生成器 def gen(): for x in ["a", "b", "c"]: yield x for i in gen(): print(i) # a b c
# yield接收值, 协程 def gen(): while True: x = yield print("x = %s"% x) g = gen() next(g) # 执行到yield, 激活协程 send(None) ”预激(prime)“协程 g.send(10) g.send(20) g.send(30) g.close() """ x = 10 x = 20 x = 30 """
yield from
yield from调用生成器
# 调用生成器 def gen(): yield from ["x", "y", "z"] for i in gen(): print(i) # x y z
参考