Skip to content

Generator

一句话解释

generator 是 函数 那个 produces 值 lazily using yield, pausing 之间 每个 值 直到 下一个 是 requested.

用大白话说

generator 是函数那个 uses yield to produce values one at a time. Instead of computing all values and returning them at once (like a list), a generator computes each value on demand, pausing between yields.

This makes generators memory-efficient — you can process infinite sequences or huge datasets without loading everything into memory. When you call a generator function, it returns a generator object (an iterator), not the values themselves.

Each call to 下一个() (or each iteration in a for loop) resumes the generator, runs until the next yield, and produces that value. When the function ends, StopIteration is raised automatically.

示例

python
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
for _ in range(8):
    print(next(fib), end=" ")
# Output: 0 1 1 2 3 5 8 13

Generators use yield 到 produce 值 lazily. 这个 fibonacci generator 是 无限 但 仅 computes 值 as requested.

常见混淆

  • 容易混淆的对象: 列表

    关键区别: 列表 存储 所有 值 in memory at 一次. generator produces 值 one at 时间 on demand. Generators 是 memory-efficient 但 能 仅 是 iterated 一次 (use 列表() 到 collect 所有 值 如果 需要).

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表