[英]A value is missing in my iterator and I don't know why
I've got a very basic generator where you can send during the loop a new value through the yield callback: 我有一个非常基本的生成器,您可以在其中在循环期间通过yield回调发送新值:
def GenInter(x, y):
while (x+1 < y):
callback = (yield x)
if callback is not None:
x = callback
else:
x += 1
Then, I create a generator: 然后,我创建一个生成器:
myGen = GenInter(10,25)
And finally, I'm parsing it with a for loop. 最后,我使用for循环对其进行解析。 When it's "15", I want to go directly to "20".
当它是“ 15”时,我想直接转到“ 20”。
for x in myGen:
if x == 15:
myGen.send(20)
print(x)
Here is the result: 结果如下:
10
11
12
13
14
15
21
22
23
How come the "20" value is missing? 为什么缺少“ 20”值?
Thank you for your help. 谢谢您的帮助。
The problem is that the send
call actually runs an iteration and returns a value and you aren't doing anything with it. 问题是
send
调用实际上会运行一个迭代并返回一个值,而您对此却无计可施。
Try this: 尝试这个:
print(myGen.send(20))
https://repl.it/repls/RuddyConcretePrinters https://repl.it/repls/RuddyConcretePrinters
As pointed out by @Imreal and by @Abarnert, myGen.send(20)
yields the missing 20. You can resolve your issue by changing your iteration to this: 正如@Imreal和@Abarnert指出的那样,
myGen.send(20)
产生缺少的20。您可以通过将迭代更改为以下内容来解决问题:
for x in myGen:
y = x
if x == 15:
y = myGen.send(20)
print(y)
It returns the following output: 它返回以下输出:
10
11
12
13
14
20
21
22
23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.