Skip to main content
Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Itertools (高性能迭代器工具库)

🚀 1. itertools 是什么?

itertools 是 Python 内置的高性能迭代器工具库,专门用于:

  • 处理可迭代对象
  • 构造无限序列
  • 组合 / 排列 / 笛卡尔积
  • 按条件分组
  • 高效数据流水线处理

所有工具都实现为 惰性生成器,节省内存,非常适合处理大数据流。

🧩 2. itertools 模块全表(速查版)

📦 核心分类

分类 函数 用途
无限迭代器 count(), cycle(), repeat() 无限生成数字/循环/重复值
按输入迭代器生成组合 accumulate(), chain(), compress(), dropwhile(), takewhile(), filterfalse(), islice(), starmap(), zip_longest() 过滤、切片、拼接、映射
组合数学类 product(), combinations(), combinations_with_replacement(), permutations() 排列组合、笛卡尔积
分组 groupby() 按 key 分组

📌 3. 无限迭代器

3.1 count(start=0, step=1)

像 range(),但无限增长。

from itertools import count

for i in count(10, 2):
    print(i)
    if i > 20:
        break

输出:

10 12 14 16 18 20 22

3.2 cycle(iterable)

无限循环序列:

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

3.3 repeat(value, times=None)

重复生成相同值:

from itertools import repeat

for x in repeat("Hi", 3):
    print(x)

输出:

Hi Hi Hi

📌 4. 按输入迭代器生成组合的工具

4.1 accumulate(iterable, func=operator.add)

累计值(加法、乘法、最大值、最小值)。

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]

4.2 chain(*iterables)

拼接多个 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]])

4.3 compress(data, selectors)

根据 True/False 选择值:

from itertools import compress
print(list(compress("ABCDE", [1,0,1,0,1])))

输出:

['A','C','E']

4.4 dropwhile(func, iterable)

遇到 False 才开始输出:

from itertools import dropwhile

print(list(dropwhile(lambda x: x < 5, [1,3,7,4,10])))

输出:

[7,4,10]

4.5 takewhile(func, iterable)

与 dropwhile 反向:

from itertools import takewhile
print(list(takewhile(lambda x: x < 5, [1,3,7,4,10])))

输出:

[1,3]

4.6 filterfalse(func, iterable)

相当于 not func(x):

from itertools import filterfalse
print(list(filterfalse(lambda x: x%2, range(6))))

输出:

[0,2,4]

4.7 islice(iterable, start, stop, step)

生成器版切片:

from itertools import islice

print(list(islice(range(10), 2, 8, 2)))

输出:

[2,4,6]

4.8 starmap(func, iterable)

将每个元素拆包作为参数:

from itertools import starmap
print(list(starmap(pow, [(2,5), (3,2), (10,3)])))

输出:

[32,9,1000]

4.9 zip_longest(a, b, fillvalue=None)

补齐较短的 iterable:

from itertools import zip_longest
print(list(zip_longest("ABC", "12", fillvalue="_")))

输出:

[('A','1'), ('B','2'), ('C','_')]

📌 5. 组合数学工具

5.1 product(*iterables, repeat=1)

笛卡尔积:

from itertools import product
print(list(product("AB", "12")))

输出:

[('A','1'), ('A','2'), ('B','1'), ('B','2')]

5.2 permutations(iterable, r=None)

排列(次序 matters):

from itertools import permutations
print(list(permutations("ABC", 2)))

输出:

[('A','B'), ('A','C'), ('B','A'), ('B','C'), ...]

5.3 combinations(iterable, r)

组合(不含重复):

from itertools import combinations
print(list(combinations("ABC", 2)))

输出:

[('A','B'), ('A','C'), ('B','C')]

5.4 combinations_with_replacement(iterable, r)

组合(允许对同一个元素重复选):

from itertools import combinations_with_replacement
print(list(combinations_with_replacement("ABC", 2)))

输出:

[('A','A'), ('A','B'), ('A','C'), ('B','B'), ...]

📌 6. 分组工具 groupby

⚠️ 关键点:必须先排序!

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)]

🌟 7. itertools 实战:数据处理流水线(高级)

假设你想:

  • 从 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]

非常流畅!

☘️ 8. itertools 的“惰性”实现优势

  • 不会一次性加载全部数据
  • 非常适合大文件流
  • 适合实时数据
  • 内存占用极低

🎯 9. 最常用的 12 个 itertools(你重点掌握即可)

类型 函数
无限迭代器 count, repeat, cycle
高效序列处理 islice, chain, accumulate, compress, starmap, filterfalse
数据组合 product, permutations, combinations
分组 groupby