[英]Why does next(some_generator_func()) yield a different result from next(a_var), where a_var = some_generator_fun()?
Let some_generator_func() be the function:让 some_generator_func() 成为函数:
def some_generator_fun():
yield 1
yield 2
Why is it that为什么是这样
>>>>next(some_generator_func())
1
>>>>next(some_generator_func())
1
whereas然而
>>>>a_var = some_generator_func()
>>>>next(a_var)
1
>>>>next(a_var)
2
? ?
In your first case, you create a new generator expression each time you call the function.在第一种情况下,每次调用函数时都会创建一个新的生成器表达式。 This means you will create a brand new generator, then call
next
which will effectively call the first element each time.这意味着您将创建一个全新的生成器,然后调用
next
每次都会有效地调用第一个元素。
When you assign it to a variable, you are yielding elements from that generator each time you call next
.当你将它分配给一个变量时,你每次调用
next
时都会从该生成器中产生元素。
Calling some_generator_func
creates a new iterator starting from the top of the function.调用
some_generator_func
从函数的顶部开始创建一个新的迭代器。 Therefore, in the first case, you iterate two fresh iterators;因此,在第一种情况下,您迭代两个新的迭代器; in the latter case, you iterate the same iterator twice.
在后一种情况下,您迭代同一个迭代器两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.