itertools
itertools 提供一组惰性迭代器工具。它们按需产生数据,适合处理大序列和组合数据,避免不必要的中间列表。
无限迭代器
from itertools import count, cycle, repeat, islice
print(list(islice(count(10, 2), 4))) # [10, 12, 14, 16]
print(list(islice(cycle("AB"), 5))) # ['A', 'B', 'A', 'B', 'A']
print(list(repeat("ok", 3))) # ['ok', 'ok', 'ok']
count、cycle 会无限运行,必须用 islice、takewhile 等设置边界。
链接、切片与分组
from itertools import chain, pairwise, takewhile, groupby
print(list(chain([1, 2], [3])))
print(list(pairwise("abcd"))) # [('a','b'), ('b','c'), ('c','d')]
print(list(takewhile(lambda n: n < 4, [1, 3, 5, 2])))
rows = sorted([("A", 1), ("B", 2), ("A", 3)])
for key, items in groupby(rows, key=lambda row: row[0]):
print(key, list(items))
groupby 只合并相邻且键相同的元素,分组前通常要按同一键排序;分组迭代器不能脱离循环后再使用。
组合与笛卡尔积
from itertools import product, permutations, combinations
print(list(product("AB", repeat=2)))
print(list(permutations("ABC", 2)))
print(list(combinations("ABC", 2)))
组合结果数量可能呈指数增长。先估算规模,必要时使用生成器逐个消费,并通过条件过滤。
迭代器管道
from itertools import compress, filterfalse, starmap
values = [10, 20, 30]
print(list(compress(values, [True, False, True])))
print(list(filterfalse(lambda n: n % 2, range(6))))
print(list(starmap(pow, [(2, 3), (3, 2)])))
迭代器通常只能消费一次;需要多次遍历时显式转换为列表,或重新创建迭代器。itertools.batched() 在 Python 3.12+ 可将数据分批,旧版本可用切片循环实现。