python生成器yield语句not yield [英] python generator yield statement not yield
本文介绍了python生成器yield语句not yield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我正在运行的代码:
Here is code I am running:
def infinite_Third() -> Generator:
num = 1
while True:
if num % 3 ==0:
i = (yield num)
if i is not None:
num = i
num += 1
if __name__=='__main__':
third_gen = infinite_Third()
for i in third_gen:
print(f"it is {i}")
if i>1000:
break
third_gen.send(10*i+1)
我希望看到的结果是:
it is 3
it is 33
it is 333
it is 3333
但是,我真正得到的是:
However, what I really get is:
it is 3
it is 36
it is 366
it is 3666
我认为这可能与在主代码中使用 send
有关,但无法弄清楚原因.有人可以帮忙吗?
I think this might be related to using send
in the main code, but couldn't figure out why. Can anyone help?
推荐答案
在我的评论之后,我已经修改了您的主循环
Follow up from my comment, I've modified your main loop
- 首先,我们发送
None
来启动生成器并接收第一个值 - 之后,我们发送一个值并接收下一个值
- First, we send a
None
to start the generator and receive the first value - After that, we send one value and receive the next one
if __name__ == '__main__':
third_gen = infinite_Third()
i = third_gen.send(None)
while True:
print(f"it is {i}")
i = third_gen.send(10*i+1)
if i > 1000:
break
这篇关于python生成器yield语句not yield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文