Skip to content

生成器与迭代器

中等 约 30 分钟

你将构建什么

一组生成器:fibonacci(无限)、chunker(将可迭代对象分块)和惰性过滤/转换大数据流的流水线。

学习目标

  • 用 yield 惰性产出值
  • 编写无限生成器
  • 将生成器链成流水线
  • 与基于列表的方法比较内存使用

前置要求

  • for 循环与可迭代对象
  • 函数
  • 列表推导式

步骤

  1. 1

    编写 Fibonacci 生成器

    生成器用 yield 逐个产出值,每个之间暂停。编写无限 Fibonacci 生成器——永不返回,但永远 yield。

    代码
    def fibonacci():
        a, b = 0, 1
        while True:
            yield a
            a, b = b, a + b
    
    # Take the first 10 values
    fib = fibonacci()
    print([next(fib) for _ in range(10)])
    # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

    预期结果

    前 10 个 Fibonacci 数:[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]。

  2. 2

    使用 itertools.islice

    由于生成器无限,用 itertools.islice 取有限个值,而非列表切片(会永远挂起)。

    代码
    from itertools import islice
    
    print(list(islice(fibonacci(), 15)))
    # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

    预期结果

    前 15 个 Fibonacci 数的列表。

  3. 3

    编写分块生成器

    编写从可迭代对象产出大小为 n 的块的生成器。这对批处理有用,无需全部加载到内存。

    代码
    def chunker(iterable, size):
        chunk = []
        for item in iterable:
            chunk.append(item)
            if len(chunk) == size:
                yield chunk
                chunk = []
        if chunk:
            yield chunk  # yield the remaining partial chunk
    
    for chunk in chunker(range(10), 3):
        print(chunk)
    # [0, 1, 2], [3, 4, 5], [6, 7, 8], [9]

    预期结果

    四个块:三个大小 3,一个大小 1。

  4. 4

    构建处理流水线

    链式生成器:读数字、过滤偶数、平方、取前 5。每步是生成器,整条流水线惰性——直到消费输出才运行。

    代码
    def numbers():
        n = 0
        while True:
            yield n
            n += 1
    
    def evens(src):
        for n in src:
            if n % 2 == 0:
                yield n
    
    def squared(src):
        for n in src:
            yield n * n
    
    pipeline = squared(evens(numbers()))
    print(list(islice(pipeline, 5)))
    # [0, 4, 16, 36, 64]

    预期结果

    前 5 个偶数平方:[0, 4, 16, 36, 64]。

  5. 5

    与列表比较内存

    展示处理 1000 万数字的生成器使用常量内存,而列表会用约 80MB。用 sys.getsizeof 比较。

    代码
    import sys
    
    # Generator: ~128 bytes regardless of how many it could produce
    gen = (x**2 for x in range(10_000_000))
    print(f"Generator size: {sys.getsizeof(gen)} bytes")
    
    # List: would be ~80MB for 10M integers
    # lst = [x**2 for x in range(10_000_000)]  # don't actually run this
    print("A list of 10M ints would be ~80MB")

    预期结果

    生成器约 128 字节;列表会是数 MB。

自己动手试试

你学到了什么

你掌握了生成器——Python 以常量内存处理大型或无限数据流的方式。它们驱动文件迭代、流式处理和异步流水线。

相关资源

相关课程

  • 循环

    生成器是 for 循环中使用的可迭代对象。

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

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

查看错误

← 返回主题