Itertools (高性能迭代器工具库)
itertools 是 Python 内置的高性能迭代器工具库,专门用于:
- 处理可迭代对象
- 构造无限序列
- 组合 / 排列 / 笛卡尔积
- 按条件分组
- 高效数据流水线处理
所有工具都实现为 惰性生成器,节省内存,非常适合处理大数据流。
📦 核心分类
| 分类 | 函数 | 用途 |
|---|---|---|
| 无限迭代器 | count(), cycle(), repeat() | 无限生成数字/循环/重复值 |
| 按输入迭代器生成组合 | accumulate(), chain(), compress(), dropwhile(), takewhile(), filterfalse(), islice(), starmap(), zip_longest() | 过滤、切片、拼接、映射 |
| 组合数学类 | product(), combinations(), combinations_with_replacement(), permutations() | 排列组合、笛卡尔积 |
| 分组 | groupby() | 按 key 分组 |
像 range(),但无限增长。
from itertools import count
for i in count(10, 2):
print(i)
if i > 20:
break
输出:
10 12 14 16 18 20 22
无限循环序列:
from itertools import cycle
count = 0
for c in cycle("AB"):
print(c)
count += 1
if count == 6:
break
输出:
A B A B A B
重复生成相同值:
from itertools import repeat
for x in repeat("Hi", 3):
print(x)
输出:
Hi Hi Hi
累计值(加法、乘法、最大值、最小值)。
from itertools import accumulate
import operator
print(list(accumulate([1,2,3,4])))
print(list(accumulate([1,2,3,4], operator.mul)))
输出:
[1, 3, 6, 10]
[1, 2, 6, 24]
拼接多个 iterable:
from itertools import chain
print(list(chain("ABC", "123")))
输出:
['A','B','C','1','2','3']
chain.from_iterable(iterable)
输入是可迭代对象:
chain.from_iterable([[1,2], [3,4]])
根据 True/False 选择值:
from itertools import compress
print(list(compress("ABCDE", [1,0,1,0,1])))
输出:
['A','C','E']
遇到 False 才开始输出:
from itertools import dropwhile
print(list(dropwhile(lambda x: x < 5, [1,3,7,4,10])))
输出:
[7,4,10]
与 dropwhile 反向:
from itertools import takewhile
print(list(takewhile(lambda x: x < 5, [1,3,7,4,10])))
输出:
[1,3]
相当于 not func(x):
from itertools import filterfalse
print(list(filterfalse(lambda x: x%2, range(6))))
输出:
[0,2,4]
生成器版切片:
from itertools import islice
print(list(islice(range(10), 2, 8, 2)))
输出:
[2,4,6]
将每个元素拆包作为参数:
from itertools import starmap
print(list(starmap(pow, [(2,5), (3,2), (10,3)])))
输出:
[32,9,1000]
补齐较短的 iterable:
from itertools import zip_longest
print(list(zip_longest("ABC", "12", fillvalue="_")))
输出:
[('A','1'), ('B','2'), ('C','_')]
笛卡尔积:
from itertools import product
print(list(product("AB", "12")))
输出:
[('A','1'), ('A','2'), ('B','1'), ('B','2')]
排列(次序 matters):
from itertools import permutations
print(list(permutations("ABC", 2)))
输出:
[('A','B'), ('A','C'), ('B','A'), ('B','C'), ...]
组合(不含重复):
from itertools import combinations
print(list(combinations("ABC", 2)))
输出:
[('A','B'), ('A','C'), ('B','C')]
组合(允许对同一个元素重复选):
from itertools import combinations_with_replacement
print(list(combinations_with_replacement("ABC", 2)))
输出:
[('A','A'), ('A','B'), ('A','C'), ('B','B'), ...]
⚠️ 关键点:必须先排序!
from itertools import groupby
data = [("A",1), ("A",2), ("B",1), ("B",3)]
for k, g in groupby(data, key=lambda x: x[0]):
print(k, list(g))
输出:
A [('A',1), ('A',2)]
B [('B',1), ('B',3)]
假设你想:
- 从 1 到 1000 的数字中
- 过滤掉奇数
- 转换成平方
- 取前 5 个
使用 itertools:
from itertools import islice
result = islice(
(x*x for x in range(1000) if x % 2 == 0),
5
)
print(list(result))
输出:
[0, 4, 16, 36, 64]
非常流畅!
- 不会一次性加载全部数据
- 非常适合大文件流
- 适合实时数据
- 内存占用极低
| 类型 | 函数 |
|---|---|
| 无限迭代器 | count, repeat, cycle |
| 高效序列处理 | islice, chain, accumulate, compress, starmap, filterfalse |
| 数据组合 | product, permutations, combinations |
| 分组 | groupby |