Python:产量和产量分配 [英] Python: yield and yield assignment
问题描述
这段涉及赋值和yield运算符的代码是如何工作的?结果相当令人困惑.
def test1(x):对于 x 中的 i:_ = 收益 i屈服 _def test2(x):对于 x 中的 i:_ = 收益 ir1 = test1([1,2,3])r2 = test2([1,2,3])打印列表(r1)打印列表(r2)
输出:
[1, None, 2, None, 3, None][1, 2, 3]
赋值语法(yield 表达式")允许您将生成器视为基本的协程.
首次在 PEP 342 中提出并记录在此处:https://docs.python.org/2/reference/expressions.html#yield-expressions
与生成器一起工作的客户端代码可以使用其 send()
方法将数据传送回生成器.该数据可通过赋值语法访问.
send()
也会迭代 - 所以它实际上包含一个 next()
调用.
以您的示例为例,这就是使用协程功能的效果:
<预><代码>>>>定义测试1(x):...对于 x 中的 i:... _ = 收益 i... 屈服 _...>>>l = [1,2,3]>>>gen_instance = test1(l)>>>#第一次发送必须是无>>>打印 gen_instance.send(无)1>>>打印 gen_instance.send("A")一种>>>打印 gen_instance.send("B")2>>>打印 gen_instance.send("C")C>>>打印 gen_instance.send("D")3>>>打印 gen_instance.send("E")乙>>>打印 gen_instance.send("F")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中停止迭代请注意,由于每个循环迭代中的第二个 yield
没有捕获已发送的数据,因此某些发送会丢失.
忘了解释你的例子中产生的 None
.
来自 https://docs.python.org/2/reference/expressions.html#generator.next:
<块引用>当使用 next() 方法恢复生成器函数时,当前yield 表达式的计算结果始终为 None.
next()
在使用迭代语法时使用.
How does this code, involving assignment and the yield operator, work? The results are rather confounding.
def test1(x):
for i in x:
_ = yield i
yield _
def test2(x):
for i in x:
_ = yield i
r1 = test1([1,2,3])
r2 = test2([1,2,3])
print list(r1)
print list(r2)
Output:
[1, None, 2, None, 3, None]
[1, 2, 3]
The assignment syntax ("yield expression") allows you to treat the generator as a rudimentary coroutine.
First proposed in PEP 342 and documented here: https://docs.python.org/2/reference/expressions.html#yield-expressions
The client code that is working with the generator can communicate data back into the generator using its send()
method. That data is accessible via the assignment syntax.
send()
will also iterate - so it actually includes a next()
call.
Using your example, this is what it would be like to use the couroutine functionality:
>>> def test1(x):
... for i in x:
... _ = yield i
... yield _
...
>>> l = [1,2,3]
>>> gen_instance = test1(l)
>>> #First send has to be a None
>>> print gen_instance.send(None)
1
>>> print gen_instance.send("A")
A
>>> print gen_instance.send("B")
2
>>> print gen_instance.send("C")
C
>>> print gen_instance.send("D")
3
>>> print gen_instance.send("E")
E
>>> print gen_instance.send("F")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Note that some of the sends are lost because of the second yield
in each loop iteration that doesn't capture the sent data.
EDIT:
Forgot to explain the None
s yielded in your example.
From https://docs.python.org/2/reference/expressions.html#generator.next:
When a generator function is resumed with a next() method, the current yield expression always evaluates to None.
next()
is used when using the iteration syntax.
这篇关于Python:产量和产量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!