本文介绍了值在python生成器/协同程序中丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看,其中我我发现非常有趣,但在一个例子中有一种我不理解的行为。

I was looking at http://www.dabeaz.com/coroutines/, which I am finding very interesting, but in an example there is a behavior I do not understand.

在示例,此处报告

# 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循环。

The sequence of numbers generated is 5, 2, 1, 0, and I can not understand where the number 3 is gone: after the send(3), the variable n is correctly set, but at the second execution of yield, it looks like the value 3 is just non yielded to the for loop.

有人可以澄清我为什么会这样?

Can someone clarify me why this happen?

推荐答案

从<$返回 3 c $ c> .send(),但丢弃了。生成器生成 5 , 3 , 2 , 1 , 0 ;但由于 3 返回到 .send()调用,因此您看不到打印的值。 循环的永远不会看到它。

The 3 was returned from .send(), but discarded. The generator produces 5, 3, 2, 1, 0; but because the 3 is returned to the .send() call you don't see that value printed. The for loop never gets to see it.

这是怎么回事:


  • 第一次 for 循环调用 next() on生成器,代码前进,直到 5 得到。

  • x == 5 是 True ,因此调用 c.send(3)。代码通过生成器函数前进, newvalue 设置为 3 。

  • 生成器暂停,它现在有控制权。生成器运行而循环并返回(yield n)表达式。产生了 3 。它成为 c.send(3)的返回值。这里将丢弃返回值。

  • 循环的继续,调用 next()再次。再次继续生成器 yield 返回无,循环到 n - = 1 并且屈服 2 。

  • for 循环继续在生成器上调用 next(), 1 和 0 产生,生成器结束。

  • first time the for loop calls next() on the generator, the code advances until 5 is yielded.
  • x == 5 is True, so c.send(3) is called. The code advances through the generator function, and newvalue is set to 3.
  • The generator does not pause there, it now has control. The generator runs through the while loop and comes back to the (yield n) expression. 3 is yielded. It becomes the return value for c.send(3). The return value is discarded here.
  • The for loop continues, calls next() again. The generator is continued again with yield returning None, loops round to n -= 1 and yielding 2.
  • The for loop continues to call next() on the generator, 1 and 0 are yielded, the generator ends.

从:

强调我的。

这篇关于值在python生成器/协同程序中丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:21