Python生成器-浮点((产量))?
我正在阅读以下关于Python生成器的教程 它包含以下代码:Python生成器-浮点((产量))?,python,generator,yield,Python,Generator,Yield,我正在阅读以下关于Python生成器的教程 它包含以下代码: def running_avg(): "coroutine that accepts numbers and yields their running average" total = float((yield)) count = 1 while True: i = yield total / count count += 1 total += i 我
def running_avg():
"coroutine that accepts numbers and yields their running average"
total = float((yield))
count = 1
while True:
i = yield total / count
count += 1
total += i
我不明白浮动((收益率))的含义。我认为
yield
用于从生成器“返回”值。这是否是对收益率的不同使用 这是一种扩展的yield
协同程序语法
请阅读以下内容:
是,
产量
也可以通过发送到生成器来接收:
>>> avg_gen = running_avg()
>>> next(avg_gen) # prime the generator
>>> avg_gen.send(1.0)
1.0
>>> print avg_gen.send(2.0)
1.5
传递给的任何值都由yield
表达式返回。请参阅文档
yield
是Python 2.5中的一个表达式;以前它只是一个语句,只为生成器生成值。通过使yield
成为一个表达式并添加.send()
(以及其他发送异常的方法),生成器现在可以简单地使用;有关此更改的初始动机,请参见