Python:收益和收益分配 [英] Python: yield and yield assignment

查看:148
本文介绍了Python:收益和收益分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码(涉及赋值和yield运算符)如何工作?结果相当令人困惑.

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)

输出:

[1, None, 2, None, 3, None] 
[1, 2, 3]

推荐答案

赋值语法(收益表达式")使您可以将生成器视为基本的协程.

The assignment syntax ("yield expression") allows you to treat the generator as a rudimentary coroutine.

首先在 PEP 342 中提出,并在此处记录: https://docs.python.org/2/reference/expressions.html#yield-expressions

First proposed in PEP 342 and documented here: https://docs.python.org/2/reference/expressions.html#yield-expressions

与生成器一起使用的客户端代码可以使用其send()方法将数据传递回生成器.可以通过赋值语法访问该数据.

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()也会迭代-因此它实际上包括一个next()调用.

send() will also iterate - so it actually includes a next() call.

使用您的示例,这就是使用couroutine功能的样子:

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

请注意,由于每次循环迭代中的第二个yield不能捕获已发送的数据,因此某些发送丢失了.

Note that some of the sends are lost because of the second yield in each loop iteration that doesn't capture the sent data.

忘了解释您的示例中产生的None.

Forgot to explain the Nones yielded in your example.

来自 https://docs.python.org/2/reference/expressions.html#generator.next :

当使用next()方法恢复生成器功能时,当前 yield表达式的计算结果始终为None.

When a generator function is resumed with a next() method, the current yield expression always evaluates to None.

使用迭代语法时使用

next().

next() is used when using the iteration syntax.

这篇关于Python:收益和收益分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆