【Python 工具人快餐 · 第 2 份】
开袋即食
itertools 是「循环加速器」:
无限迭代器、排列组合、滑动窗口、分批读取……
全部惰性生成,内存永远只占一条缝。
1 行代码 4 连发
from itertools import count, islice, product, pairwisec = islice(count(10, 2), 5) # [10,12,14,16,18] 无限迭代切 5 片
p = list(product('AB', repeat=2)) # [('A','A'), ('A','B'), ...]
w = list(pairwise(range(4))) # [(0,1),(1,2),(2,3)]
场景实拍:大文件按 1 MB 块读取
需求:逐块处理 10 GB 日志,却不撑爆内存。
from pathlib import Path
from itertools import islicedef chunked(file, size=1_024_000):while chunk := file.read(size):yield chunkwith Path('giant.log').open('rb') as f:for piece in chunked(f):process(piece) # 内存永远只有 1 MB
核心工具:iter(callable, sentinel)
的魔法,这里换成 while
更直观。
升级加料
- 组合:
combinations('ABC', 2)
→ AB AC BC - 累积:
accumulate([1,2,3,4])
→ 1 3 6 10 - 分组:
groupby(sorted(data, key=key), key=key)
打包带走 : 循环太长?先看 itertools! 惰性迭代器,内存永动机。