Python 的 带send的协程

等级 5276 次按键

这演示了通过send()接收值并返回累计平均值的协程。

Python 代码

# 基于生成器的协程,维护累计平均值
1def running_average():
# total 保持所有值的总和
2 total = 0
# count 跟踪接收的值的数量
3 count = 0
# average 存储当前的累计平均值
4 average = None
# 无限循环以持续接收值
5 while True:
# yield 暂停并返回 average,接收新值
6 value = yield average
# 仅当发送了值(非 None)时处理
7 if value is not None:
# 将值添加到累计总和
8 total += value
# 增加计数
9 count += 1
# 计算新平均值
10 average = total / count
11
# 创建协程对象
12coro = running_average()
# 通过推进到第一个 yield 来启动协程
13next(coro)
# 发送 10,得到平均值 10.0
14print(coro.send(10))
# 发送 20,得到平均值 15.0
15print(coro.send(20))
# 发送 30,得到平均值 20.0
16print(coro.send(30))
# 通过关闭协程来清理
17coro.close()

运行结果

10.0
15.0
20.0
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • (× 10
  • )× 10
  • =× 8
  • .× 4
  • :× 3
  • _× 2
  • +× 2
  • /× 1

Python 等级 5 的更多代码示例

← 返回 Python 打字练习