使用生成器
def generator(): print(123) yield 1 print(456) yield 2 g = generator() ret = g.__next__() print(ret) ret = g.__next__() print(ret)
send
def generator(): print(123) content = yield 1 print("====",content) print(456) yield 2 g = generator() ret = g.__next__() print(ret) ret = g.send("hello") print(ret)
send 获取先一个值的效果和next基本一致,只是在获取下一个值的时候,给上一个值的位置传递一个数控
注意:第一次使用生成器器的时候,必须要使用next获取下一个值
最后一个yield不能接受外部的值
获取移动平均值
每给一个数取一次平均值
def average(): sum = 0 count = 0 avg = 0 while True: num = yield avg #在这里返回 sum += num count += 1 avg = sum/count avg_g = average() avg_g.__next__() avg1 = avg_g.send(10) avg1 = avg_g.send(20) print(avg1)
from
def generator(): a = "ABCDE" b = "12345" yield from a yield from b g = generator() for i in g : print(i) 执行结果: A B C D E 1 2 3 4 5