python的协程例子:每次输入一个数字,然后计算出所有输入数字的平均值

#!/usr/bin/env python3

def mean_x():
    s = 0.0
    n = 0
    while True:
        s += yield
        n+=1
        print("s =", s, "n=", n)
        print("mean = ", s/n)

x = mean_x()
next(x)
while True:
    print("please input number...")
    x.send(float(input()))

能写出类似的例子,就是理解协程了。

猜你喜欢

转载自blog.csdn.net/u011539200/article/details/81039846
今日推荐