Effective Python 条款36:优雅拼装迭代器与生成器
- 一、连接多个迭代器:把多股数据流拼在一起🧩
-
- [1. chain:拼接多个迭代器](#1. chain:拼接多个迭代器)
- [2. repeat:无限 / 有限重复同一个元素](#2. repeat:无限 / 有限重复同一个元素)
- [3. cycle:循环遍历序列](#3. cycle:循环遍历序列)
- [4. tee:一个迭代器分裂成多份](#4. tee:一个迭代器分裂成多份)
- [5. zip_longest:不等长迭代器配对补齐](#5. zip_longest:不等长迭代器配对补齐)
- 二、过滤源迭代器:筛选你想要的数据🎯
-
- [1. islice:迭代器版本切片](#1. islice:迭代器版本切片)
- [2. takewhile:条件成立就持续拿元素](#2. takewhile:条件成立就持续拿元素)
- [3. dropwhile:跳过开头符合条件的元素](#3. dropwhile:跳过开头符合条件的元素)
- [4. filterfalse:留下条件为 False 的元素](#4. filterfalse:留下条件为 False 的元素)
- 三、基于源迭代器合成新元素🧮
-
- [1. accumulate:迭代式累计计算](#1. accumulate:迭代式累计计算)
- [2. product:笛卡尔积,干掉多层嵌套循环](#2. product:笛卡尔积,干掉多层嵌套循环)
- [3. permutations:有序排列](#3. permutations:有序排列)
- [4. combinations:无序组合(不允许重复选取元素)](#4. combinations:无序组合(不允许重复选取元素))
- [5. combinations_with_replacement:允许重复选取的组合](#5. combinations_with_replacement:允许重复选取的组合)
- [✨写在最后:itertools 使用要点总结](#✨写在最后:itertools 使用要点总结)
写 Python 的时候,处理循环、遍历、数据流,我们总爱手写 for 循环、嵌套推导式。但很多复杂迭代逻辑,不用自己 "从零造轮子"。Python 标准库自带的
itertools模块,就是迭代器的工具箱,里面封装了大量开箱即用的迭代工具,能帮我们写出更简短、高效、可读性更强的生成器代码。
如果你正在写复杂的迭代逻辑,不要急着埋头撸循环,优先打开交互终端敲下 import itertools; help(itertools),翻翻官方文档,大概率能找到现成的工具函数。
itertools 的工具可以分为三大类:连接多个迭代器 、过滤迭代器元素 、基于原有元素合成新元素。下面我们结合示例代码,逐个搞懂它们的用法、适用场景和潜在坑点。
一、连接多个迭代器:把多股数据流拼在一起🧩
这一组函数负责把若干迭代器拼接、复制、拆分、循环,处理多数据源的遍历场景。
1. chain:拼接多个迭代器
chain 可以把多个迭代器 / 可迭代对象首尾相连,合成一个大迭代器。它不会创建完整列表,是惰性迭代,不会一次性把全部数据加载进内存。
python
import itertools
# 将两个列表无缝拼接
it = itertools.chain([1, 2, 3], [4, 5, 6])
print(list(it)) # [1, 2, 3, 4, 5, 6]
💡性能提示:对比
list1 + list2,+运算符会生成全新列表,复制全部数据;chain只是在迭代时依次消费各个输入,面对百万级大序列,内存优势非常明显。
2. repeat:无限 / 有限重复同一个元素
想要反复输出同一个对象,就用 repeat。不传第二个参数会无限生成该值;传入数字就限定重复次数。
python
# 重复输出字符串3次
it = itertools.repeat('hello', 3)
print(list(it)) # ['hello', 'hello', 'hello']
⚠️注意:它不是复制对象!迭代输出的是同一个对象的多次引用。如果是可变对象,修改其中一个,全部结果都会跟着变化。
3. cycle:循环遍历序列
cycle 接收一个可迭代对象,无限循环输出里面的元素。
python
it = itertools.cycle([1, 2])
# 取10个元素
result = [next(it) for _ in range(10)]
print(result) # [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
🚨坑提醒:
cycle默认是无限迭代!千万不要直接list(itertools.cycle([1,2])),会直接卡死程序。一定要做次数限制。
4. tee:一个迭代器分裂成多份
普通迭代器一旦被遍历消耗,就没了。tee 可以把同一个源迭代器,拆分成 N 个独立的并行迭代器。
python
it1, it2, it3 = itertools.tee(['first', 'second'], 3)
print(list(it1)) # ['first', 'second']
print(list(it2)) # ['first', 'second']
print(list(it3)) # ['first', 'second']
⚠️重要性能提醒:
如果拆分出来的几个迭代器推进速度差距很大,跑得慢的迭代器还没取走的数据,会全部放在内存缓冲区缓存。如果数据量巨大,会带来可观的内存开销。尽量保证各个副本迭代进度不要相差太远。
5. zip_longest:不等长迭代器配对补齐
内置 zip() 有个痛点:只要任意一个迭代器耗尽,整体就直接终止。
itertools.zip_longest() 可以解决这个问题,短的迭代器耗尽后,会用 fillvalue 填充空位,直到最长的迭代器完成。
python
keys = ['one', 'two', 'three']
values = [1, 2]
normal = list(zip(keys, values))
print("zip: ", normal) # zip: [('one', 1), ('two', 2)]
it = itertools.zip_longest(keys, values, fillvalue="nope")
longest = list(it)
print("zip_longest: ", longest)
# zip_longest: [('one', 1), ('two', 2), ('three', 'nope')]
二、过滤源迭代器:筛选你想要的数据🎯
这一组函数从原始迭代流中筛选、剔除部分元素,依然保持惰性求值,不生成中间列表。
1. islice:迭代器版本切片
普通列表切片 lst[2:8:2] 需要序列支持下标访问。而迭代器本身不能下标取值,islice 就充当迭代器的切片工具,支持起点、终点、步长,不会拷贝原始数据。
python
values = [1,2,3,4,5,6,7,8,9,10]
# 取前5个
first_five = itertools.islice(values, 5)
print("First five: ", list(first_five)) # First five: [1, 2, 3, 4, 5]
# 从下标2开始,到下标8结束,步长2
middle_odds = itertools.islice(values, 2, 8, 2)
print("Middle odds: ", list(middle_odds)) # Middle odds: [3, 5, 7]
2. takewhile:条件成立就持续拿元素
takewhile(predicate, iterable):只要判断函数返回 True,就持续取出元素;一旦遇到 False,立刻停止迭代。
python
values = [1,2,3,4,5,6,7,8,9,10]
less_than_seven = lambda x: x <7
it = itertools.takewhile(less_than_seven, values)
print(list(it)) # [1, 2, 3, 4, 5, 6]
3. dropwhile:跳过开头符合条件的元素
和 takewhile 正好反过来。一直跳过元素,直到判断函数返回 True;从这个元素开始,返回后面全部剩余元素,不再做判断。
python
values = [1,2,3,4,5,6,7,8,9,10]
less_than_seven = lambda x: x <7
it = itertools.dropwhile(less_than_seven, values)
print(list(it)) # [7, 8, 9, 10]
4. filterfalse:留下条件为 False 的元素
内置 filter() 保留判断函数返回 True 的元素;filterfalse 则保留返回 False 的元素。想要筛选出不满足条件的数据,不用写取反的 lambda。
python
values = [1,2,3,4,5,6,7,8,9,10]
is_even = lambda x: x %2 ==0
filter_res = filter(is_even, values)
print("filter: ", list(filter_res)) # filter: [2, 4, 6, 8, 10]
filter_false_res = itertools.filterfalse(is_even, values)
print("Filter false: ", list(filter_false_res)) # Filter false: [1, 3, 5, 7, 9]
三、基于源迭代器合成新元素🧮
这一类工具做组合、累积、排列笛卡尔积等计算,常常用来替代多层嵌套循环。
1. accumulate:迭代式累计计算
accumulate 类似简化版的 functools.reduce。
区别在于:reduce 只输出最终一个结果;accumulate 会输出每一步的累计中间结果。不传入二元函数,默认做累加。
python
values = [1,2,3,4,5,6,7,8,9,10]
sum_reduce = itertools.accumulate(values)
print("Sum: ", list(sum_reduce))
# Sum: [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
# 自定义累计逻辑:每次相加后对20取模
def sum_mod_20(a, b):
return (a + b) % 20
mod_reduce = itertools.accumulate(values, sum_mod_20)
print("Modulo: ", list(mod_reduce))
# Modulo: [1, 3, 6, 10, 15, 1, 8, 16, 5, 15]
2. product:笛卡尔积,干掉多层嵌套循环
写多层嵌套循环生成组合,代码又丑又深。product 用来计算笛卡尔积,repeat=N 等价于把同一个序列重复 N 份做乘积。
python
# 单序列,repeat=2,相当于双重循环
single = itertools.product([1,2], repeat=2)
print('Single: ', list(single))
# Single: [(1, 1), (1, 2), (2, 1), (2, 2)]
# 多个不同序列的笛卡尔积
multi = itertools.product([1,2], ["a","b"])
print('Multiple: ', list(multi))
# Multiple: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
3. permutations:有序排列
从序列选 N 个元素,生成全部有序排列,顺序不同视为不同结果。
python
it = itertools.permutations([1,2,3,4], 2)
print(list(it))
# [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
4. combinations:无序组合(不允许重复选取元素)
选取 N 个元素,不考虑顺序,(1,2) 和 (2,1) 视为同一个,只会输出一次。
python
it = itertools.combinations([1,2,3,4], 2)
print(list(it))
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
5. combinations_with_replacement:允许重复选取的组合
和 combinations 逻辑接近,但允许同一个元素被多次选中。
python
it = itertools.combinations_with_replacement([1,2,3,4], 2)
print(list(it))
# [(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]
✨写在最后:itertools 使用要点总结
-
itertools的工具分为三大阵营:连接迭代器、过滤元素、合成新元素,绝大多数复杂迭代场景,都可以由它们组合完成。 -
绝大多数返回值都是迭代器,惰性求值,不会一次性把全部数据加载内存,处理超大数据流很友好;但无限迭代器(
cycle、repeat)千万不要直接强转 list,防止程序卡死。 -
使用
tee需要注意:各个拆分副本迭代进度差距过大,会带来额外内存缓冲开销。 -
本文只展示高频 API,模块还有更多宝藏函数,记得用
help(itertools)翻阅官方文档,里面附带参数说明与示例代码。

不要一上来就手写复杂嵌套 for 循环。优先站在巨人肩膀上,善用标准库工具,你的代码会更加简洁、健壮、优雅。