itertools 模块
提供了一系列的迭代器工具,这些工具可以创建复杂的迭代器
一.无限迭代器
count(start=0, step=1) - 返回一个无限迭代器,从 start 开始,每次递增 step。
cycle(iterable) - 对传入的可迭代对象进行无限循环。
repeat(object, times=None) - 无限重复对象,除非指定了 times。
二.有限迭代器
- itertools.accumulate(iterable[, func, *, initial=None])
默认使用加法
from itertools import accumulate
# 默认情况下,accumulate 会累加数字
numbers = (1, 2, 3, 4, 5)
result = list(accumulate(numbers))
print(result) # 输出: [1, 3, 6, 10, 15]
使用自定义函数
from itertools import accumulate
# 使用自定义的乘法函数进行累积
numbers = (1, 2, 3, 4, 5)
result = list(accumulate(numbers, lambda x, y: x * y))
print(result) # 输出: [1, 2, 6, 24, 120]
使用初始值
from itertools import accumulate
# 使用初始值
numbers = (1, 2, 3, 4, 5)
initial_value = 10
result = list(accumulate(numbers, initial=initial_value))
print(result) # 输出: [10, 11, 13, 16, 20, 25]
- chain(iterables) - 将多个可迭代对象串联成一个迭代器。
from itertools import chain
arr = list(chain('123', '456'))
print(arr) # 输出:['1', '2', '3', '4', '5', '6']
三.排列组合迭代器
- itertools.product 函数是 Python itertools模块中的一个非常有用的工具,它用于生成可迭代对象的笛卡尔积。
from itertools import product
arr = list(product([1,3],[4,6]))
print(arr)
brr = list(product("ad", repeat = 2))
print(brr)
crr = list(product("12","34"))
print(crr)
输出
[(1, 4), (1, 6), (3, 4), (3, 6)]
[('a', 'a'), ('a', 'd'), ('d', 'a'), ('d', 'd')]
[('1', '3'), ('1', '4'), ('2', '3'), ('2', '4')]
- permutations 函数返回输入可迭代对象的所有可能排列。排列是序列中元素的所有可能顺序。
from itertools import permutations
print(list(permutations('ABC',2)))
print(list(permutations([1,2,3])))
输出
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
- combinations 函数返回输入可迭代对象的所有可能组合。组合是序列中元素的子集,不考虑元素的顺序。
from itertools import permutations
print(list(combinations('ABCD', 2)))
print(list(combinations([1,2,3,4], 3)))
输出
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]