一、【说在前面】
看到这篇文章的大兄弟您们好,我们经常说调包侠、CRUD仔,用来鄙视不会自己造轮子的工程师,不过笔者认为python的精髓就是调库。库很快,自己写大概率更慢。调包侠也是有高低贵贱之分的,今天介绍一个特别好用的库——itertools
这个库会自动产生一些诸如:排列、组合、笛卡尔积、多迭代器整合、zip等。更详细可以看这个官网一手资料。
itertools — Functions creating iterators for efficient looping — Python 3.12.1 documentation
二、【正式介绍】
(1)无限循环迭代器
-  count(start[, step]):- count()函数生成一个从- start开始的无限递增的整数序列。如果提供了- step参数,则按照步长递增。
- Arguments: - start: 序列的起始值,默认为 0。
- step: 序列的步长,默认为 1。
 
- Results: - 生成一个无限递增的整数序列。
 
- Example: from itertools import count # 从10开始,步长为2,不写默认步长为1 for i in count(10, 2): print(i)# 10,12,14,16……
 
-  cycle(iterable):- cycle()函数接受一个可迭代对象,并无限循环输出该可迭代对象的元素。
- Arguments: - iterable: 要循环的可迭代对象。
 
- Results: - 无限循环输出可迭代对象的元素。
 
- Example: from itertools import cycle # 无限循环输出 'A', 'B', 'C' for elem in cycle('ABC'): print(elem)
 
-  repeat(elem [,n]): 
repeat() 函数生成一个无限重复输出某个元素的序列,或者最多重复 n 次。不写n则会一直重复
Arguments:
elem: 要重复的元素。
n: 最多重复的次数,默认为无限次。
Results:
生成一个无限重复输出元素的序列,或者最多重复 n 次。
Example:
from itertools import repeat # 重复输出数字 10,最多重复 3 次 
for elem in repeat(10, 3): print(elem)(2)最短序列终止迭代器
1. accumulate(p [,func]):
将可迭代对象中的元素累积起来,可指定累积的函数。
Example:
from itertools import accumulate # 累积和 
result = accumulate([1, 2, 3, 4, 5]) 
print(list(result)) # 输出 [1, 3(1+2), 6(1+2+3), 10, 15]2. batched(p, n):
将可迭代对象划分为大小为 n 的批次。
Example:
from itertools import batched # 划分为大小为 3 的批次 
result = batched('ABCDEFG', n=3) 
print(list(result)) # 输出 [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]3. chain(p, q, …):
将多个可迭代对象连接成一个单一的迭代器。
Example:
from itertools import chain # 连接两个字符串 result = chain('ABC', 'DEF') 
print(list(result)) # 输出 ['A', 'B', 'C', 'D', 'E', 'F']4. chain.from_iterable(iterable):
与 chain 类似,但接受一个可迭代对象的可迭代对象。
Example:
from itertools import chain # 连接两个字符串列表 
result = chain.from_iterable(['ABC', 'DEF']) 
print(list(result)) # 输出 ['A', 'B', 'C', 'D', 'E', 'F']5. compress(data, selectors):
返回一个通过选择器筛选的数据元素序列。
Example:
from itertools import compress # 通过选择器筛选数据 
result = compress('ABCDEF', [1, 0, 1, 0, 1, 1]) # 1有0无
print(list(result)) # 输出 ['A', 'C', 'E', 'F']6. dropwhile(pred, seq):
返回在预测失败之后的序列元素。
Example:
from itertools import dropwhile # 在预测失败之后的序列元素 
result = dropwhile(lambda x: x < 5, [1, 4, 6, 4, 1])  # 当遇到第一个不满足条件(即大于等于 5)的元素时,停止迭代并返回余下的元素 [6, 4, 1]
print(list(result)) # 输出 [6, 4, 1]7. filterfalse(pred, seq):
返回使预测结果为假的序列元素。
Example:
from itertools import filterfalse # 使预测结果为假的序列元素 
result = filterfalse(lambda x: x % 2, range(10)) # 与2取模,奇数会留1所以不显示print(list(result)) # 输出 [0, 2, 4, 6, 8]8. groupby(iterable[, key]):
根据键函数对序列进行分组。
笔者记得,力扣有一道压缩算法,比如sss44444改为s3,45,就可以拿这个做,
Example:
from itertools import groupby # 根据首字母分组 
result = groupby('AAAABBBCCDAABBB') 
for key, group in result: print(key, list(group)) # 输出 # A ['A', 'A', 'A', 'A'] # B ['B', 'B', 'B'] # C ['C', 'C'] # D ['D'] # A ['A', 'A'] # B ['B', 'B', 'B']9. islice(seq, [start,] stop [, step]):
返回切片后的序列元素。
Example:
from itertools import islice # 切片序列 seq[start:stop:step]
result = islice('ABCDEFG', 2, None)  # 从索引 = 2开始切,这个跟py自带的切片一个道理
print(list(result)) # 输出 ['C', 'D', 'E', 'F', 'G']10. pairwise(iterable):
返回序列中两两相邻的元素。
- Example: from itertools import pairwise # 两两相邻的元素 result = pairwise('ABCDEFG') print(list(result)) # 输出 [('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]
11. starmap(func, seq):
- 对可迭代对象中的元素应用函数,元素以参数元组的形式传递给函数。
- Example: from itertools import starmap # 应用 pow 函数 result = starmap(pow, [(2, 5), (3, 2), (10, 3)]) # 很好理解,本质就是一个map操作 print(list(result)) # 输出 [32, 9, 1000]
12. takewhile(pred, seq):
返回在预测失败之前的序列元素立即为。
Example:
python复制代码
from itertools import takewhile # 在预测失败之前的序列元素 
result = takewhile(lambda x: x < 5, [1, 4, 6, 4, 1]) 
print(list(result)) # 输出 [1, 4]13. tee(it, n):
将一个迭代器拆分成多个相同的迭代器。
Example:
from itertools import tee # 将一个迭代器拆分成两个 iter1, iter2 = tee('ABC') print(list(iter1)) # 输出 ['A', 'B', 'C'] 
print(list(iter2)) # 输出 ['A', 'B', 'C']14. zip_longest(p, q, …):
将多个迭代器中的元素逐个配对,以最长的迭代器为准,可以指定填充值。
Example:
from itertools import zip_longest # 将两个迭代器中的元素逐个配对 
result = zip_longest('ABCD', 'xy', fillvalue='-') 
print(list(result)) # 输出 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')](3)排列、组合、笛卡尔积
1. product(p, q, …, repeat=1):
 
- product函数用于计算多个可迭代对象的笛卡尔积,生成所有可能的组合。它的参数可以是多个可迭代对象,如- p, q, ...,以及一个可选的- repeat参数,用于指定重复的次数。
- 例如,如果 p是[1, 2],q是[3, 4],那么product(p, q)将生成[(1, 3), (1, 4), (2, 3), (2, 4)]
# 示例 1: product
p = [1, 2]
q = [3, 4]
result_product = list(itertools.product(p, q))
print(result_product)  # 输出:[(1, 3), (1, 4), (2, 3), (2, 4)]2. permutations(iterable, r=None):
 
- permutations函数用于生成可迭代对象中长度为- r的所有排列。它的参数包括一个可迭代对象- iterable和一个可选的- r参数,用于指定生成的排列长度。
- 例如,如果 iterable是[1, 2, 3],r是2,那么permutations(iterable, r)将生成[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)],这是长度为2的所有可能排列。
# 示例 2: permutations
iterable = [1, 2, 3]
r = 2
result_permutations = list(itertools.permutations(iterable, r))
print(result_permutations)  # 输出:[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]3. combinations(iterable, r):
 
- combinations函数用于生成可迭代对象中长度为- r的所有组合,按照排序顺序生成。它的参数包括一个可迭代对象- iterable和一个- r参数,用于指定生成的组合长度。
- 例如,如果 iterable是[1, 2, 3],r是2,那么combinations(iterable, r)将生成[(1, 2), (1, 3), (2, 3)],这是长度为2的所有可能组合,按照排序顺序生成。
# 示例 3: combinations
iterable = [1, 2, 3]
r = 2
result_combinations = list(itertools.combinations(iterable, r))
print(result_combinations)  # 输出:[(1, 2), (1, 3), (2, 3)]
4. combinations_with_replacement(iterable, r):
 
- combinations_with_replacement函数与- combinations类似,用于生成可迭代对象中长度为- r的所有组合,但不要求元素不重复,可以包含重复元素。
- 例如,如果 iterable是[1, 2],r是2,那么combinations_with_replacement(iterable, r)将生成[(1, 1), (1, 2), (2, 2)],这是长度为2的所有可能组合,包括重复元素。
# 示例 4: combinations_with_replacement
iterable = [1, 2]
r = 2
result_combinations_with_replacement = list(itertools.combinations_with_replacement(iterable, r))
print(result_combinations_with_replacement)  # 输出:[(1, 1), (1, 2), (2, 2)]