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✅这些函数是函数式编程风格的基石——链式调用、惰性求值、组合使用构建高效的数据处理管道。

相关新闻

最新新闻

Greasy Fork:如何让你的浏览器像瑞士军刀一样强大?

Greasy Fork:如何让你的浏览器像瑞士军刀一样强大?

Greasy Fork:如何让你的浏览器像瑞士军刀一样强大? 【免费下载链接】greasyfork An online repository of user scripts. 项目地址: https://gitcode.com/gh_mirrors/gr/greasyfork 你是否曾经在浏览网页时,心里默默想着:&…

2026/8/2 23:32:44
Windows 11 LTSC也能拥有完整应用商店:一键恢复微软商店的完整指南

Windows 11 LTSC也能拥有完整应用商店:一键恢复微软商店的完整指南

Windows 11 LTSC也能拥有完整应用商店:一键恢复微软商店的完整指南 【免费下载链接】LTSC-Add-MicrosoftStore Add Windows Store to Windows 11 24H2 LTSC 项目地址: https://gitcode.com/gh_mirrors/ltscad/LTSC-Add-MicrosoftStore 你是否在使用Windows 1…

2026/8/2 23:32:44
基于云函数与语义过滤的AIDD领域论文自动化简报系统构建实践

基于云函数与语义过滤的AIDD领域论文自动化简报系统构建实践

1. 项目缘起:一个信息过载研究者的自救每天早晨,我打开邮箱和学术订阅列表,面对的是几十甚至上百封来自arXiv、PubMed、各大顶会官网的论文推送。标题一个比一个吸引人,摘要一个比一个“颠覆性”,但我的时间和精力是有…

2026/8/2 23:32:44
口碑好的实体商户 AIGC 降本方案优质厂家

口碑好的实体商户 AIGC 降本方案优质厂家

在当今数字化时代,实体商户面临着诸多经营成本压力,而 AIGC 技术的出现为他们带来了降本增效的新契机。以下为您介绍一些口碑良好的提供实体商户 AIGC 降本方案的优质厂家。优变好 AI公司简介优变好 AI 隶属于上海姑获鸟科技,是一家专注于 AI…

2026/8/2 23:32:44
未来展望:NFSIISE开发路线图与社区贡献指南

未来展望:NFSIISE开发路线图与社区贡献指南

未来展望:NFSIISE开发路线图与社区贡献指南 【免费下载链接】NFSIISE Need For Speed™ II SE - Cross-platform wrapper with 3D acceleration and TCP protocol! 项目地址: https://gitcode.com/gh_mirrors/nf/NFSIISE NFSIISE作为一款跨平台的Need For Sp…

2026/8/2 23:32:44
PyPDF2技术架构深度解析:高效PDF处理的实现原理与性能优化

PyPDF2技术架构深度解析:高效PDF处理的实现原理与性能优化

PyPDF2技术架构深度解析:高效PDF处理的实现原理与性能优化 【免费下载链接】pypdf A pure-python PDF library capable of splitting, merging, cropping, and transforming the pages of PDF files 项目地址: https://gitcode.com/GitHub_Trending/py/pypdf …

2026/8/2 23:27:44