gpt4 book ai didi

python - Yield 和 yield from - 你能把它们结合起来吗?

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:54 28 4
gpt4 key购买 nike

刚发现yield from 结构,在我看来这有点像反向的yield,而不是从生成器中获取对象,您插入/将对象发送到生成器。喜欢:

def foo():
while True:
x = (yield)
print(f'{x=}')

f = foo()
f.send(None)
for i in range(4):
f.send(i)

产量:

x=0
x=1
x=2
x=3

然后我想知道你是否可以将两者结合起来。

def foo():
while True:
x = (yield)
print(f'{x=}')
yield x + 1000

f = foo()
f.send(None)
for i in range(4):
print(f'y={f.send(i)}')

那么我会期待

x=0
y=1000
x=1
y=1001
x=2
y=1002
x=3
y=1003

但是我明白了

x=0
y=1000
y=None
x=2
y=1002
y=None

谁能解释一下?

最佳答案

如果您要“将两者结合起来”,将yield 视为一个单一 点发送值,然后从外部接受值是很有用的。那样的话,您可能会理解为什么您不会每隔一行打印出一行“x=”,而在输出中每隔三行打印一次 None。这是因为 foo(..) 控件在 while block 中的每个循环中出现两次。

这是您的代码的固定版本:

def foo():
x = 0
while True:
x = (yield x + 1000)
print(f'{x=}')

f = foo()
f.send(None)
for i in range(4):
print(f'y={f.send(i)}')

关于python - Yield 和 yield from - 你能把它们结合起来吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59090758/

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