python - 生成和接收值的 Python 生成器
问题描述
有人可以解释一下 yield 在下面的代码中是如何工作的吗?
def countdown(n):
print("Counting down from", n)
while n >= 0:
newvalue = (yield n)
if newvalue is not None:
n = newvalue
else:
n -= 1
c = countdown(5)
for n in c:
print n
if n == 4:
c.send(2)
输出
('Counting down from', 5)
5
4
1
0
我希望它是
('Counting down from', 5)
5
4
2
1
0
“2”在哪里迷路了?
同时跟踪这两个事件(接收和生产)变得有点棘手。这不是python生成器“发送”功能目的的重复吗?因为这个问题主要集中在理解对协程的需求以及它们如何推迟生成器。我的问题非常具体到一起使用协程和生成器的问题。
解决方案
重复的问题有相关文档:
send() 方法返回生成器产生的下一个值[.]
那里的这个答案说明了控制如何来回移动,send()
在这里很有用。首先,添加额外print
的 s 来说明正在发生的事情:
def countdown(n):
print("Counting down from", n)
while n >= 0:
newvalue = (yield n)
print (newvalue, n) # added output
if newvalue is not None:
n = newvalue
else:
n -= 1
c = countdown(5)
for n in c:
print n
if n == 4:
print(c.send(2)) # added output.
你会看到的:
('Counting down from', 5)
5
(None, 5)
4
(2, 4)
2
(None, 2)
1
(None, 1)
0
(None, 0)
使用send(2)
, 控制传递给函数,newvalue = (yield n)
继续循环,循环一次到下一个 yield,再次停止,但是这次 yield 的值是由返回的send(2)
,而不是for 循环的下一次迭代。有你的2
。
推荐阅读
- python-3.x - 在 python 中使用函数 any() 时代码不显示任何答案
- python - 如何从我的根路径自动重定向?
- node.js - 结构指针类型的 node-ffi OUT 参数无法接收来自 DLL 调用的返回值
- javascript - 如何根据选择的选项将数据输出到表
- python - 如果需要,如何通过插入虚拟行来获得分组对角线值?
- azure - 如何在 Azure API 管理实例中远程登录
- r - 根据条件替换列集中的值
- php - Woocommerce 无需结帐即可免费下载
- cordova-facebook - facebook 插件可以与 http 一起使用多久?
- c++ - 在类中添加多引用函数类型