无法理解python生成器

San*_*u C 17 python generator

我是python中的新生成器.我有一个简单的代码,我正在玩,但我无法理解我从中得到的输出.这是我的代码:

def do_gen():
    for i in range(3):
        yield i

def incr_gen(y):
    return y + 1

def print_gen(x):
    for i in x:
        print i

x = do_gen()
y = (incr_gen(i) for i in x)
print_gen(x)
print_gen(y)
Run Code Online (Sandbox Code Playgroud)

我希望我的输出是这样的:

0  1  2 
1  2  3
Run Code Online (Sandbox Code Playgroud)

但我只看到:0 1 2

我不明白这个输出.谁能帮助我理解我缺乏理解?提前致谢.

Mar*_*ers 5

生成器(像所有迭代器一样)只能迭代一次.到时候print_gen(x),情况也是如此x.从中获取新值的任何进一步尝试x都将导致StopIteration被提升.

这有效:

x = do_gen()
y = (incr_gen(i) for i in do_gen())
print_gen(x)
print_gen(y)
Run Code Online (Sandbox Code Playgroud)

因为这会创建两个独立的独立发电机 在您的版本中,您指定的生成器表达式y期望x产生更多值.

当您依次使用它们时,更容易看到x生成器是共享的:ynext()

>>> def do_gen():
...     for i in range(3):
...         yield i
... 
>>> def incr_gen(y):
...     return y + 1
... 
>>> x = do_gen()
>>> y = (incr_gen(i) for i in x)
>>> next(x)  # first value for the range
0
>>> next(y)  # second value from the range, plus 1
2
>>> next(x)  # third value from the range
2
>>> next(y)  # no more values available, generator done
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
Run Code Online (Sandbox Code Playgroud)

注意这里StopIteration提出的next(y)也是如此.