首页 › Python 进阶 › 迭代器与生成器

迭代器与生成器

能被 for 遍历的对象叫可迭代对象。for 循环背后会调用 iter() 得到迭代器,再反复调用 next() 取值,直到抛出 StopIteration。

it = iter([1, 2, 3])
print(next(it))   # 1
print(next(it))   # 2

生成器函数

包含 yield 的函数就是生成器函数。每次 yield 返回一个值并暂停,下次从暂停处继续:

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(3):
    print(x)      # 3 2 1

为什么用生成器

生成器按需产生数据,不会一次把所有结果放进内存。处理大文件时尤其有用:

def read_lines(path):
    with open(path, encoding="utf-8") as f:
        for line in f:
            yield line.rstrip("\n")

for line in read_lines("access.log"):
    if "ERROR" in line:
        print(line)

即使日志文件有几个 GB,内存占用也只有一行的大小。

itertools

标准库 itertools 提供了很多实用的迭代工具:

from itertools import islice, count

evens = (x for x in count() if x % 2 == 0)
print(list(islice(evens, 5)))   # [0, 2, 4, 6, 8]

练习题

学完本节后,试着独立完成下面的练习,再展开参考答案对照。

练习 1 写一个生成器 chunks(items, n),每次产出 n 个元素组成的列表。

查看参考答案
def chunks(items, n):
    for i in range(0, len(items), n):
        yield items[i:i + n]

print(list(chunks(list(range(7)), 3)))
参考输出:
[[0, 1, 2], [3, 4, 5], [6]]

练习 2 写一个无限生成器产生 1, 2, 4, 8…,用 itertools.islice 取前 10 个。

查看参考答案
from itertools import islice

def powers_of_two():
    n = 1
    while True:
        yield n
        n *= 2

print(list(islice(powers_of_two(), 10)))
参考输出:
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]