首页 > 解决方案 > 生成和接收值的 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生成器“发送”功能目的的重复吗?因为这个问题主要集中在理解对协程的需求以及它们如何推迟生成器。我的问题非常具体到一起使用协程和生成器的问题。

标签: 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


推荐阅读