张芷铭的个人博客

itertools 是 Python 标准库的迭代器工具集,提供高效处理迭代对象的函数。

无限迭代器

函数说明
count(start, step)无限计数器
cycle(iterable)无限循环迭代
repeat(elem, n)重复元素 n 次
1
2
3
4
5
from itertools import count, cycle, repeat, islice

list(islice(count(), 5))        # [0, 1, 2, 3, 4]
list(islice(cycle('ABC'), 7))   # ['A','B','C','A','B','C','A']
list(repeat(1, 3))              # [1, 1, 1]

排列组合

函数说明
product(*iterables)笛卡尔积
permutations(iterable, r)排列
combinations(iterable, r)组合(无重复)
combinations_with_replacement组合(可重复)
1
2
3
4
5
from itertools import product, permutations, combinations

list(product('AB', repeat=2))   # [('A','A'), ('A','B'), ('B','A'), ('B','B')]
list(permutations('ABC', 2))    # [('A','B'), ('A','C'), ('B','A'), ...]
list(combinations('ABC', 2))    # [('A','B'), ('A','C'), ('B','C')]

筛选与分组

函数说明
filterfalse(pred, iter)过滤不满足条件的元素
takewhile(pred, iter)持续取值直到条件为假
dropwhile(pred, iter)跳过直到条件为假
groupby(iterable, key)分组
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from itertools import filterfalse, takewhile, groupby

# 过滤偶数
list(filterfalse(lambda x: x % 2, range(10)))  # [0, 2, 4, 6, 8]

# 取值直到条件为假
list(takewhile(lambda x: x < 5, [1, 3, 5, 7, 9]))  # [1, 3]

# 分组(需先排序)
for k, g in groupby('AAABBCC'):
    print(k, list(g))  # A ['A','A','A']  B ['B','B']  C ['C','C']

其他常用

函数说明
chain(*iterables)连接多个迭代器
islice(iterable, stop)切片
zip_longest(*iterables)最长 zip
1
2
3
4
5
from itertools import chain, islice, zip_longest

list(chain([1, 2], [3, 4]))         # [1, 2, 3, 4]
list(islice(range(100), 5))         # [0, 1, 2, 3, 4]
list(zip_longest([1, 2], [3], fillvalue=0))  # [(1, 3), (2, 0)]

Comments