Python 中的生成器和 for 循环

Generators and for loops in Python

所以我有一个生成器函数,看起来像这样。

def generator():
    while True:
        for x in range(3):
            for j in range(5):
                yield x

在我加载这个函数并多次调用 "next" 之后,我希望它产生值

0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 0 0 0 0 0 ...

但它始终只产生 0。这是为什么?

>>> execfile("test.py")
>>> generator
<function generator at 0x10b6121b8>
>>> generator().next()
0
>>> generator().next()
0
>>> generator().next()
0
>>> generator().next()
0
>>> generator().next()
0
>>> generator().next()
0
>>> generator().next()
0

generator() 初始化新的生成器对象:

In [4]: generator() is generator() # Creating 2 separate objects
Out[4]: False

然后 generator().next() 从新创建的生成器对象中获取第一个值(0)。

您应该调用 generator 一次:

In [5]: gen = generator() # Storing new generator object, will reuse it

In [6]: [gen.next() for _ in range(6)] # Get first 6 values for demonstration purposes
Out[6]: [0, 0, 0, 0, 0, 1]

注意generator.next was removed from Python 3 (PEP 3114) - use the next function改为:

In [7]: next(gen)
Out[7]: 1

每次调用 generator 您都在创建一个新的生成器对象:

generator().next() # 1st item in 1st generator 
generator().next() # 1st item in 2nd generator

创建一个生成器,然后为后续项目调用 next

g = generator()

g.next() # 1st item in 1st generator
g.next() # 2nd item in 1st generator

我把它贴在评论里了,我想如果你把这个和问题一起看,你就会发现错误:

with open('my_file.txt', 'r') as f: 
    print(f.readline())               # `readline` simply reads a single line

with open('my_file.txt', 'r') as f: 
    print(f.readline())

with open('my_file.txt', 'r') as f: 
    print(f.readline())

with open('my_file.txt', 'r') as f: 
    print(f.readline())    

不是每次都创建一个新的生成器对象,而是必须创建一次然后使用它直到它被耗尽:

mygen = generator()
mygen.next()
mygen.next()
...
etc