gpt4 book ai didi

Python:产量和产量分配

转载 作者:IT老高 更新时间:2023-10-28 21:02:11 26 4
gpt4 key购买 nike

这段涉及赋值和yield 运算符的代码是如何工作的?结果相当令人困惑。

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]

最佳答案

赋值语法(“yield 表达式”)允许您将生成器视为基本协程。

首次提出于 PEP 342并记录在这里:https://docs.python.org/2/reference/expressions.html#yield-expressions

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

send() 也会迭代 - 所以它实际上包含一个 next() 调用。

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

>>> 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 没有捕获发送的数据,一些发送会丢失。

编辑:忘记解释您的示例中产生的 None

来自 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() 在使用迭代语法时使用。

关于Python:产量和产量分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32128412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com