1. itertools 模块简介
itertools
模块是 Python 标准库中用于操作迭代器的工具集。迭代器是 Python 中一种强大的概念,允许我们逐个处理数据序列,而无需一次性将整个序列加载到内存中。itertools
模块提供了一系列函数,可用于创建、组合和处理迭代器,极大地简化了与迭代相关的编程任务,在处理大型数据集或需要复杂迭代逻辑的场景中非常有用。
2. 无穷迭代器
- count():生成从指定值开始的无穷整数序列。
python">import itertoolscounter = itertools.count(start = 1, step = 2)
for _ in range(5):print(next(counter))
在上述代码中,itertools.count(start = 1, step = 2)
创建了一个从 1 开始,步长为 2 的无穷整数迭代器。通过 next(counter)
获取迭代器的下一个值,这里使用 for
循环获取前 5 个值,输出为 1 3 5 7 9
。
- cycle():循环迭代给定的序列,无穷重复。
python">import itertoolscycles = itertools.cycle(['a', 'b', 'c'])
for _ in range(6):print(next(cycles))
此代码中,itertools.cycle(['a', 'b', 'c'])
创建了一个循环迭代 ['a', 'b', 'c']
序列的无穷迭代器。循环 6 次,输出为 a b c a b c
。
- repeat():重复生成一个元素,无穷次或指定次数。
python">import itertoolsrepeater = itertools.repeat('hello', times = 3)
for item in repeater:print(item)
这里 itertools.repeat('hello', times = 3)
创建了一个重复 'hello'
三次的迭代器,输出为 hello hello hello
。如果不指定 times
参数,将无穷重复。
3. 有限迭代器
- accumulate():对迭代器中的元素进行累积计算。
python">import itertools
import operatornums = [1, 2, 3, 4]
acc = itertools.accumulate(nums, operator.add)
print(list(acc))
代码中,itertools.accumulate(nums, operator.add)
对列表 nums
中的元素进行累加操作。operator.add
是用于指定累加操作的函数。输出为 [1, 3, 6, 10]
,分别是 1
,1 + 2
,1 + 2 + 3
,1 + 2 + 3 + 4
的结果。如果不指定操作函数,默认进行加法运算。
- chain():将多个迭代器连接成一个迭代器。
python">import itertoolslist1 = [1, 2]
list2 = [3, 4]
chained = itertools.chain(list1, list2)
print(list(chained))
itertools.chain(list1, list2)
将列表 list1
和 list2
连接成一个迭代器,输出为 [1, 2, 3, 4]
,就像将两个列表合并成一个序列进行迭代。
4. 组合迭代器
- product():生成多个迭代器的笛卡尔积。
python">import itertoolscolors = ['red', 'blue']
sizes = ['S', 'M']
products = itertools.product(colors, sizes)
print(list(products))
这里 itertools.product(colors, sizes)
生成了 colors
和 sizes
两个列表的笛卡尔积,输出为 [('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]
,即两个列表元素所有可能的组合。
- permutations():生成给定序列的所有排列。
python">import itertoolsnums = [1, 2, 3]
permutations_list = itertools.permutations(nums)
print(list(permutations_list))
itertools.permutations(nums)
生成列表 nums
中元素的所有排列,输出为 [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
。
- combinations():生成给定序列的所有组合(不考虑顺序)。
python">import itertoolsnums = [1, 2, 3]
combinations_list = itertools.combinations(nums, 2)
print(list(combinations_list))
itertools.combinations(nums, 2)
生成列表 nums
中元素长度为 2 的所有组合,输出为 [(1, 2), (1, 3), (2, 3)]
,组合中的元素顺序是固定的,且不包含重复组合。