苦练Python第34日:itertools玩转高阶迭代

223 阅读2分钟

前言

大家好,我是倔强青铜三。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!

欢迎来到苦练Python的第34天!

今天,我们将潜入 Python 最强大的标准库之一:itertools

如果你想:

  • 生成各种组合
  • 创建无限序列
  • 或者把多个可迭代对象串成一条“流水线”

那么 itertools 就是你最值得信赖的伙伴。


🧰 什么是 itertools

itertools 模块提供了一套快速、省内存的工具,全部基于迭代器,帮你把循环写出“高级感”。


🔢 1. 无限迭代器

这些函数会永不停歇地产生数据(直到你主动喊停)。

count(start=0, step=1)

from itertools import count

for i in count(10, 2):
    print(i)
    if i > 20:
        break

输出:
10, 12, 14, 16, 18, 20, 22


cycle(iterable)

把同一个可迭代对象无限循环下去。

from itertools import cycle

for item in cycle(['A', 'B', 'C']):
    print(item)
    break  # 记得用 break 终止

repeat(item, times)

重复同一个元素指定次数。

from itertools import repeat

for item in repeat('Hello', 3):
    print(item)

输出:
Hello
Hello
Hello


🔁 2. 组合迭代器

专治排列、组合、笛卡尔积,优雅的暴力美学。

product()

from itertools import product

colors = ['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 permutations

for p in permutations([1, 2, 3], 2):
    print(p)

combinations(iterable, r)

返回所有无序组合

from itertools import combinations

for c in combinations([1, 2, 3], 2):
    print(c)

🔗 3. 工具迭代器

过滤、拼接、切片、分组,一条龙服务。

chain()

把多个可迭代对象连成一条

from itertools import chain

for i in chain([1, 2], ['A', 'B']):
    print(i)

islice()

像列表切片一样切迭代器

from itertools import islice

for i in islice(range(100), 10, 15):
    print(i)

输出:
10 11 12 13 14


compress(data, selectors)

用布尔序列过滤数据。

from itertools import compress

data = 'ABCDEF'
selectors = [1, 0, 1, 0, 1, 0]

print(list(compress(data, selectors)))  # ['A', 'C', 'E']

📌 实战场景速查表

任务推荐函数
生成所有穿搭组合product()
大数据切片islice()
无限轮询状态cycle()
投票计数模拟repeat()
排班表排列permutations()

🧪 迷你练习

  1. 列出 "ABC" 的所有 3 字母排列。
  2. 给定两个列表,生成所有颜色-尺码组合。
  3. 把 3 个列表串成一条迭代器。

🧠 小贴士

itertools 返回的是迭代器,不是列表。
需要立即结果可用 list() 收集,但记得:不转换更省内存

最后感谢阅读!欢迎关注我,微信公众号倔强青铜三。欢迎点赞收藏关注,一键三连!!!