Python模块:内置模块itertools迭代工具全解析

发布时间:2026/8/2 22:52:46
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) —— 无限计数counteritertools.count(10,2)# 从10开始每次2print([next(counter)for_inrange(5)])# [10, 12, 14, 16, 18]# cycle(iterable) —— 无限循环cycleritertools.cycle([A,B,C])print([next(cycler)for_inrange(7)])# [A, B, C, A, B, C, A]# repeat(obj, times) —— 重复timesNone表示无限repeateritertools.repeat(Hello,3)print(list(repeater))# [Hello, Hello, Hello]# ⚠️ 无限迭代器会一直生成元素需要手动控制停止# 通常搭配 islice 或 break 使用三、有限迭代器3.1 拼接和展平importitertools# chain(*iterables) —— 拼接多个迭代器resultlist(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]]flatlist(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, stepnumbersrange(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:x5,data)))# [5, 2, 4, 6, 1, 3]# takewhile(predicate, iterable) —— 取开头的满足条件的元素print(list(itertools.takewhile(lambdax:x5,data)))# [1, 3]# filterfalse(predicate, iterable) —— 保留假值filter的反向print(list(itertools.filterfalse(lambdax:x%20,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[(技术部,张三),(技术部,李四),(市场部,王五),(市场部,赵六),]# keylambda x: x[0] 等于按部门分组fordept,membersinitertools.groupby(data,keylambdax:x[0]):names[m[1]forminmembers]print(f{dept}:{, .join(names)})# 技术部: 张三, 李四# 市场部: 王五, 赵六# ⚠️ groupby只能合并相邻的相同key——如果数据未排序先排序# pairwise(iterable) —— 相邻元素配对Python 3.10print(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,repeat2)))# [(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)]# 实战生成骰子所有可能的组合dicerange(1,7)# 1-6all_outcomeslist(itertools.product(dice,repeat2))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):创建滑动窗口iteratorsitertools.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✅这些函数是函数式编程风格的基石——链式调用、惰性求值、组合使用构建高效的数据处理管道。