python "send"方法不会更改 "next"的值?

标签 python generator return-value send yield

我正在尝试生成器的发送功能,我期望发送会改变正在产生的值,所以我在 ipython 中尝试:

In [17]: def z(n):
    ...:     i=0
    ...:     while(i<n):
    ...:         val=yield i
    ...:         print "value is:",val
    ...:         i+=1
    ...:
In [24]: z1=z(10)
In [25]: z1.next()
Out[25]: 0

In [26]: z1.send(5) # I was expecting that after "send", output value will become "5"
value is: 5
Out[26]: 1

In [27]: z1.next()
value is: None # I was expecting that z1.next() will restart from "6" because I sent "5"
Out[27]: 2

嗯,我想我对“发送”的真正作用有错误的理解,如何纠正它?

最佳答案

您正在生成 i 但您没有将 yield 语句的返回值分配给它。如果您分配返回值,您将看到您期望的输出:

def z(n):
    print 'Generator started'
    i=0
    while(i<n):
        val=yield i
        print "value is:",val
        if val is not None:
            i = val
        i+=1

z1=z(10)
print 'Before start'
print z1.next()
print z1.send(5)
print z1.next()

输出:

Before start
Generator started
0
value is: 5
6
value is: None
7

更新:当第一次调用sendnext时,生成器从开始执行到第一个yield 语句,此时值返回给调用者。这就是为什么 value is: text is not seen on first call。当 sendnext 被第二次调用时,执行从 yield 恢复。如果 send 被调用,则 yield 语句返回给它的参数,否则 yield 返回 None

关于python "send"方法不会更改 "next"的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40903079/

相关文章:

python - 过滤掉生成器

python - 解密通过其他来源加密的 3DES 数据

image - 图标日历生成器

javascript - ES6 yield (yield 1)(yield 2)(yield 3)()

java - 在方法中返回文档

php - 如何在一次 ajax 调用中返回 html 代码和 php 值

javascript - 如何在 Flask 中使用 JSON 对象

python - 相同的 ImageDataGenerator 但不同的 class_indices - 如何重新映射生成器中的类?

python - 如何在 Windows 上安装 PyCairo(Python 的 Cairo)?

go - 单值上下文中的多个值