python - python 生成器/协程中的值丢失

标签 python iteration generator coroutine

我正在查看http://www.dabeaz.com/coroutines/ ,我觉得这很有趣,但在一个例子中有一个我不理解的行为。

bogus.py此处报告的示例

# bogus.py
#
# Bogus example of a generator that produces and receives values
def countdown(n):
    print "Counting down from", n
    while n >= 0:
        newvalue = (yield n)
        # If a new value got sent in, reset n with it
        if newvalue is not None:
            n = newvalue
        else:
            n -= 1

# The holy grail countdown
c = countdown(5)
for x in c:
    print x
    if x == 5:
        c.send(3)

生成的数字序列是 5, 2, 1, 0,我不明白数字 3 去了哪里:在 send(3) 之后,变量 n 设置正确,但在第二次执行 yield 时,看起来值 3 只是未在 for 循环中生成。

有人可以解释一下为什么会发生这种情况吗?

最佳答案

3.send() 返回,但被丢弃。发电机产生 5 , 3 , 2 , 1 , 0 ;但因为3返回到.send()调用您看不到打印的值。 for循环永远看不到它。

发生的事情是这样的:

  • 第一次 for循环调用next()在生成器上,代码前进直到 5已产生。
  • x == 5True ,所以c.send(3)叫做。代码通过生成器函数前进,并且 newvalue设置为3 .
  • 生成器不会在那里暂停,它现在拥有控制权。发电机运行通过while循环并返回到(yield n)表达。 3已产生。它成为 c.send(3) 的返回值。返回值在这里被丢弃。
  • for循环继续,调用 next()再次。生成器再次继续 yield返回None ,循环舍入到n -= 1并产生2 .
  • for循环继续调用next()在发电机上,10产生,生成器结束。

引自 generator.send() documentation :

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value.

强调我的。

关于python - python 生成器/协程中的值丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17990624/

相关文章:

python - Numpy - 列之间的平均距离

c - 测试迭代指针之间的关系是否安全?

java - 生成文件中的 MyBatis 异常

python - Vim python 缩进改变代码语义

python - 对列进行分组并连接多个列的唯一字符串值以创建单个列

python - 如何从 python time.time() 计算当前月份

java - 在迭代期间更改 HashMap 键

java - java 中 arrayList 与 Set 的比较

python - 生成器中无法捕获的异常

javascript - 被发电机搞糊涂了