[英]Why must I use a variable to get values from a Python generator?
Why must I use a variable to obtain next() values from a Python generator? 为什么必须使用变量从Python生成器获取next()值?
def my_gen():
i = 0
while i < 4:
yield 2 * i
i += 1
#p = my_gen()
#for i in range(4):
# print(next(p))
##for i in range(4):
## print(next(my_gen()))
In the above, the # block works, while the ## block returns 4 copies of the first "yield." 在上面的代码中,#块起作用,而##块返回第一个“产量”的4个副本。
print(next(my_gen()))
Each time this runs, you're calling next()
on a separate (and brand-new) generator returned by my_gen()
. 每次运行时,您都在由
my_gen()
返回的单独(全新)生成器上调用next()
my_gen()
。
If you want to call next()
on the same generator more than once, you'll need some way to keep that generator around for long enough to reuse it. 如果要在同一生成器上多次调用
next()
,则需要某种方法来使该生成器保持足够长的时间,以重用它。
just gonna add my $0.02... 只需加上我的$ 0.02 ...
this may help clear up some misconceptions: 这可能有助于清除一些误解:
def function_that_creates_a_generator(n):
while n>0:
yield n
n - 1
# this
for x in function_that_creates_a_generator(5):
print(x)
#is almost exactly the same as this
generator = function_that_creates_a_generator(5)
while True:
try:
x = generator.next() #same as: x = next(generator)
except StopIteration:
break
print(x)
For loops are really just a prettier way of writing a while loop that continually asks an iterable object for its next element. For循环实际上只是编写while循环的一种更漂亮的方式,该循环不断向可迭代对象请求下一个元素。 when you ask an iterable for another object and it has none, it will raise a
StopIteration
exception that is automatically caught in for loops; 当您请求一个可迭代对象而另一个对象没有对象时,它将引发
StopIteration
异常,该异常会自动陷入for循环中; signaling a break from the loop. 从循环中发出信号。 In the while loop we simply break these things out individually instead of having them hidden by the interpreter.
在while循环中,我们只是将这些东西单独分解,而不是将它们隐藏在解释器中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.