第 48 章 / 70 · 高级 · 标准库深入
itertools 模块
chain / combinations / permutations / groupby
先介绍1 个 demo6 个任务答案可展开
一、本章介绍
itertools 提供高效的迭代器工具:chain 连接、combinations 组合、permutations 排列、groupby 分组。它们惰性计算,处理大数据省内存。
这一章从连接到排列,最后用 groupby 分组收尾。
本章要点
- chain 连接
- combinations 组合
- permutations 排列
- groupby 分组
二、先看 demo
下面这个例子把本章涉及的用法尽量全面地串了一遍,代码带逐行注释,可以直接复制到本地 .py 文件运行。
案例
先看一个完整例子
介绍 · 逐行注释from itertools import chain,combinations,permutations,groupby
print(list(chain([1,2],[3,4])))
print(list(combinations([1,2,3],2)))
print(list(permutations([1,2],2)))
data=[("A",1),("A",2),("B",3)]
data.sort(key=lambda x:x[0])
for k,g in groupby(data,key=lambda x:x[0]):
print(k,[v for _,v in g])运行结果
[1, 2, 3, 4]
[(1, 2), (1, 3), (2, 3)]
[(1, 2), (2, 1)]
A [1, 2]
B [3]要点:chain 拼接、combinations 无序组合、permutations 有序排列;groupby 前要先按 key 排序。
三、6 个任务(自己先写,再看答案)
难度从入门到挑战逐步增加。每个任务的答案默认折叠,点开可看参考代码、运行结果;有第二种解法的也一并给出。代码都可以直接运行。
任务 1
连接列表
自己写 · 附答案入门 ★☆☆解题提示:本题主要用到 chain 连接、combinations 组合、permutations 排列。先对照要求自己写一遍,卡住了再展开答案。
用 chain 把 [1,2] 和 [3,4] 连起来
参考答案(先自己写,再看)
参考答案一
from itertools import chain
print(list(chain([1,2],[3,4])))运行结果
[1, 2, 3, 4]参考答案二(另一种解法)
print([1,2]+[3,4])任务 2
组合
自己写 · 附答案入门 ★☆☆解题提示:本题主要用到 chain 连接、combinations 组合、permutations 排列。先对照要求自己写一遍,卡住了再展开答案。
用 combinations 求 [1,2,3] 选 2 的组合
参考答案(先自己写,再看)
参考答案一
from itertools import combinations
print(list(combinations([1,2,3],2)))运行结果
[(1, 2), (1, 3), (2, 3)]参考答案二(另一种解法)
print([(1,2),(1,3),(2,3)])任务 3
排列
自己写 · 附答案进阶 ★★☆解题提示:本题主要用到 chain 连接、combinations 组合、permutations 排列。先对照要求自己写一遍,卡住了再展开答案。
用 permutations 求 [1,2] 的全排列
参考答案(先自己写,再看)
参考答案一
from itertools import permutations
print(list(permutations([1,2])))运行结果
[(1, 2), (2, 1)]参考答案二(另一种解法)
print([(1,2),(2,1)])任务 4
重复元素
自己写 · 附答案进阶 ★★☆解题提示:本题主要用到 chain 连接、combinations 组合、permutations 排列。先对照要求自己写一遍,卡住了再展开答案。
用 repeat 生成 3 个 7
参考答案(先自己写,再看)
参考答案一
from itertools import repeat
print(list(repeat(7,3)))运行结果
[7, 7, 7]参考答案二(另一种解法)
print([7]*3)任务 5
累积和
自己写 · 附答案挑战 ★★★解题提示:本题主要用到 chain 连接、combinations 组合、permutations 排列。先对照要求自己写一遍,卡住了再展开答案。
用 accumulate 求 [1,2,3,4] 的累加过程
参考答案(先自己写,再看)
参考答案一
from itertools import accumulate
print(list(accumulate([1,2,3,4])))运行结果
[1, 3, 6, 10]参考答案二(另一种解法)
import itertools
print(list(itertools.accumulate(range(1,5))))任务 6
分组统计
自己写 · 附答案挑战 ★★★解题提示:本题主要用到 chain 连接、combinations 组合、permutations 排列。先对照要求自己写一遍,卡住了再展开答案。
用 groupby 把 [("a",1),("a",2),("b",3)] 按 key 分组求和
参考答案(先自己写,再看)
参考答案一
from itertools import groupby
d=[("a",1),("a",2),("b",3)]
d.sort(key=lambda x:x[0])
print({k:sum(v for _,v in g) for k,g in groupby(d,key=lambda x:x[0])})运行结果
{'a': 3, 'b': 3}参考答案二(另一种解法)
from collections import defaultdict
r=defaultdict(int)
for k,v in [("a",1),("a",2),("b",3)]: r[k]+=v
print(dict(r))