Python模块:内置模块itertools迭代工具全解析
Python模块:内置模块itertools迭代工具全解析
一、开篇:迭代器的瑞士军刀
itertools是Python标准库中的"高性能迭代工具箱"——所有函数都用C实现,比手写的Python循环快得多。它提供了构建高效迭代管道的积木块:无限序列、组合生成、分组过滤、累积计算。
⌨️ 三大类工具:
importitertools# 1. 无限迭代器:count, cycle, repeat# 2. 有限迭代器:accumulate, chain, compress, groupby 等# 3. 组合迭代器:product, permutations, combinations二、无限迭代器
importitertools# count(start, step) —— 无限计数counter=itertools.count(10,2)# 从10开始,每次+2print([next(counter)for_inrange(5)])# [10, 12, 14, 16, 18]# cycle(iterable) —— 无限循环cycler=itertools.cycle(["A","B","C"])print([next(cycler)for_inrange(7)])# ['A', 'B', 'C', 'A', 'B', 'C', 'A']# repeat(obj, times) —— 重复(times=None表示无限)repeater=itertools.repeat("Hello",3)print(list(repeater))# ['Hello', 'Hello', 'Hello']# ⚠️ 无限迭代器会一直生成元素,需要手动控制停止# 通常搭配 islice 或 break 使用三、有限迭代器
3.1 拼接和展平
importitertools# chain(*iterables) —— 拼接多个迭代器result=list(itertools.chain([1,2],[3,4],[5,6]))print(result)# [1, 2, 3, 4, 5, 6]# chain.from_iterable —— 展平嵌套结构nested=[[1,2],[3,4],[5,6]]flat=list(itertools.chain.from_iterable(nested))print(flat)# [1, 2, 3, 4, 5, 6]# 展平更深的结构(自定义函数)defflatten(nested_list):"""递归展平任意深度的嵌套列表"""foriteminnested_list:ifisinstance(item,list):yieldfromflatten(item)else:yielditem deep=[1,[2,[3,4],5],6]print(list(flatten(deep)))# [1, 2, 3, 4, 5, 6]3.2 切片和过滤
importitertools# islice(iterable, stop) —— 切片(支持start, stop, step)numbers=range(100)print(list(itertools.islice(numbers,5)))# [0, 1, 2, 3, 4]print(list(itertools.islice(numbers,10,15)))# [10, 11, 12, 13, 14]print(list(itertools.islice(numbers,0,20,5)))# [0, 5, 10, 15]# dropwhile(predicate, iterable) —— 跳过开头的满足条件的元素data=[1,3,5,2,4,6,1,3]print(list(itertools.dropwhile(lambdax:x<5,data)))# [5, 2, 4, 6, 1, 3]# takewhile(predicate, iterable) —— 取开头的满足条件的元素print(list(itertools.takewhile(lambdax:x<5,data)))# [1, 3]# filterfalse(predicate, iterable) —— 保留假值(filter的反向)print(list(itertools.filterfalse(lambdax:x%2==0,range(10))))# [1, 3, 5, 7, 9]# compress(data, selectors) —— 按布尔掩码过滤data=["A","B","C","D","E"]mask=[True,False,True,False,True]print(list(itertools.compress(data,mask)))# ['A', 'C', 'E']3.3 累加和分组
importitertools# accumulate(iterable, func) —— 累积计算numbers=[1,2,3,4,5]print(list(itertools.accumulate(numbers)))# [1, 3, 6, 10, 15] 累加print(list(itertools.accumulate(numbers,max)))# [1, 2, 3, 4, 5] 到当前位置的最大值print(list(itertools.accumulate(numbers,lambdaa,b:a*b)))# [1, 2, 6, 24, 120] 累乘# groupby(iterable, key) —— 按key分组(需要先排序!)data=[("技术部","张三"),("技术部","李四"),("市场部","王五"),("市场部","赵六"),]# key=lambda x: x[0] 等于按部门分组fordept,membersinitertools.groupby(data,key=lambdax:x[0]):names=[m[1]forminmembers]print(f"{dept}:{', '.join(names)}")# 技术部: 张三, 李四# 市场部: 王五, 赵六# ⚠️ groupby只能合并相邻的相同key——如果数据未排序,先排序!# pairwise(iterable) —— 相邻元素配对(Python 3.10+)print(list(itertools.pairwise([1,2,3,4,5])))# [(1,2), (2,3), (3,4), (4,5)]四、组合迭代器
importitertools items=["A","B","C"]# product(*iterables, repeat) —— 笛卡尔积print(list(itertools.product(items,repeat=2)))# [('A','A'), ('A','B'), ('A','C'), ('B','A'), ('B','B'), ('B','C'), ('C','A'), ('C','B'), ('C','C')]# permutations(iterable, r) —— 排列(顺序重要)print(list(itertools.permutations(items,2)))# [('A','B'), ('A','C'), ('B','A'), ('B','C'), ('C','A'), ('C','B')]# combinations(iterable, r) —— 组合(顺序不重要)print(list(itertools.combinations(items,2)))# [('A','B'), ('A','C'), ('B','C')]# combinations_with_replacement —— 有放回组合print(list(itertools.combinations_with_replacement(items,2)))# [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')]# 实战:生成骰子所有可能的组合dice=range(1,7)# 1-6all_outcomes=list(itertools.product(dice,repeat=2))print(f"两个骰子有{len(all_outcomes)}种结果")五、实战案例
importitertools# 案例:生成测试数据的笛卡尔积defgenerate_test_cases():"""生成测试用例矩阵"""browsers=["Chrome","Firefox","Safari"]os_list=["Windows","Mac","Linux"]resolutions=["1920x1080","1366x768"]forbrowser,os_name,resinitertools.product(browsers,os_list,resolutions):yield{"browser":browser,"os":os_name,"resolution":res}print(f"共{sum(1for_ingenerate_test_cases())}个测试用例")# 案例:滑动窗口defsliding_window(iterable,n):"""创建滑动窗口"""iterators=itertools.tee(iterable,n)fori,itinenumerate(iterators):for_inrange(i):next(it,None)returnzip(*iterators)data=[1,2,3,4,5,6,7,8]forwindowinsliding_window(data,3):print(window)# (1, 2, 3) (2, 3, 4) (3, 4, 5) ...六、总结
itertools是构建高效数据处理管道的工具箱。用C实现的迭代器比手写Python循环快得多。
💡核心函数速查:
- 无限序列:
count,cycle,repeat - 拼接展平:
chain,chain.from_iterable - 切片过滤:
islice,takewhile,dropwhile,compress,filterfalse - 累积分组:
accumulate,groupby - 组合生成:
product,permutations,combinations
✅这些函数是函数式编程风格的基石——链式调用、惰性求值、组合使用,构建高效的数据处理管道。
