前言
大家好,我是倔强青铜三。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!
欢迎来到苦练Python的第34天!
今天,我们将潜入 Python 最强大的标准库之一:itertools
。
如果你想:
- 生成各种组合创建无限序列或者把多个可迭代对象串成一条“流水线”
那么 itertools
就是你最值得信赖的伙伴。
🧰 什么是 itertools
?
itertools
模块提供了一套快速、省内存的工具,全部基于迭代器,帮你把循环写出“高级感”。
🔢 1. 无限迭代器
这些函数会永不停歇地产生数据(直到你主动喊停)。
count(start=0, step=1)
from itertools import countfor i in count(10, 2): print(i) if i > 20: break
输出:
10, 12, 14, 16, 18, 20, 22
cycle(iterable)
把同一个可迭代对象无限循环下去。
from itertools import cyclefor item in cycle(['A', 'B', 'C']): print(item) break # 记得用 break 终止
repeat(item, times)
重复同一个元素指定次数。
from itertools import repeatfor item in repeat('Hello', 3): print(item)
输出:
Hello
Hello
Hello
🔁 2. 组合迭代器
专治排列、组合、笛卡尔积,优雅的暴力美学。
product()
from itertools import productcolors = ['red', 'blue']sizes = ['S', 'M']for combo in product(colors, sizes): print(combo)
输出:
('red', 'S')
('red', 'M')
('blue', 'S')
('blue', 'M')
permutations(iterable, r=None)
返回所有可能的有序排列。
from itertools import permutationsfor p in permutations([1, 2, 3], 2): print(p)
combinations(iterable, r)
返回所有无序组合。
from itertools import combinationsfor c in combinations([1, 2, 3], 2): print(c)
🔗 3. 工具迭代器
过滤、拼接、切片、分组,一条龙服务。
chain()
把多个可迭代对象连成一条。
from itertools import chainfor i in chain([1, 2], ['A', 'B']): print(i)
islice()
像列表切片一样切迭代器。
from itertools import islicefor i in islice(range(100), 10, 15): print(i)
输出:
10 11 12 13 14
compress(data, selectors)
用布尔序列过滤数据。
from itertools import compressdata = 'ABCDEF'selectors = [1, 0, 1, 0, 1, 0]print(list(compress(data, selectors))) # ['A', 'C', 'E']
📌 实战场景速查表
任务 | 推荐函数 |
---|---|
生成所有穿搭组合 | product() |
大数据切片 | islice() |
无限轮询状态 | cycle() |
投票计数模拟 | repeat() |
排班表排列 | permutations() |
🧪 迷你练习
- 列出 "ABC" 的所有 3 字母排列。给定两个列表,生成所有颜色-尺码组合。把 3 个列表串成一条迭代器。
🧠 小贴士
itertools
返回的是迭代器,不是列表。
需要立即结果可用 list()
收集,但记得:不转换更省内存!
最后感谢阅读!欢迎关注我,微信公众号:
倔强青铜三
。欢迎点赞
、收藏
、关注
,一键三连!!!