[英]python generator yield statement 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)
I am expecting to see results as:我期待看到如下结果:
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
I think this might be related to using send
in the main code, but couldn't figure out why.我认为这可能与在主代码中使用send
有关,但无法弄清楚原因。 Can anyone help?谁能帮忙?
Follow up from my comment, I've modified your main loop根据我的评论跟进,我已经修改了你的主循环
None
to start the generator and receive the first value首先,我们发送一个None
来启动生成器并接收第一个值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
I managed to make it working as you expect by adding extra yield to infinite_Third()
but frankly i don't know why it works.我设法通过向infinite_Third()
添加额外的收益使其按您预期的方式工作,但坦率地说,我不知道它为什么会起作用。
def infinite_Third() -> Generator:
num = 1
while True:
if num % 3 ==0:
i = yield num
if i is not None:
num = i
yield
num += 1
It seems that, every time send()
is called, an extra None
value is put to the generator buffer and extra yield
looks like consuming that.看起来,每次调用send()
时,都会将一个额外的None
值放入生成器缓冲区,额外的yield
看起来像是在消耗它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.