← 中文资源

简体中文版本

itertools 的 product、combinations 与 permutations

product 把多个序列展开成笛卡尔积(repeat= 可自乘),combinations 取无序组合,permutations 保留顺序取排列:同一输入下数量与形态一目了然。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

product: [('s', 'red'), ('s', 'blue'), ('m', 'red'), ('m', 'blue')]
dice: [(1, 1), (1, 2), (1, 3), (1, 4)] ...
combinations: [('a', 'b'), ('a', 'c'), ('b', 'c')]
permutations: [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
counts: 2-pick 3 2-perm 6

实现说明

顶层就这几处状态:sizes、colors。

使用要点

  • 每一步打印都带着自己的标签:product:、dice:、combinations:。

常见问题

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。 文件用顶层绑定保存自己的状态:sizes、colors。

代码示例

from itertools import combinations, permutations, product

# product:笛卡尔积——每个输入序列各取一个,穷举所有搭配
sizes = ["s", "m"]
colors = ["red", "blue"]
print("product:", list(product(sizes, colors)))

# repeat= 把单个序列与自身做 n 次笛卡尔积:两颗骰子的点数组合
print("dice:", list(product(range(1, 7), repeat=2))[:4], "...")

# combinations:组合无序,同一组元素只出现一次
print("combinations:", list(combinations("abc", 2)))

# permutations:排列有序,同样的输入数量是组合的两倍
print("permutations:", list(permutations("abc", 2)))

print("counts: 2-pick", len(list(combinations("abc", 2))), "2-perm", len(list(permutations("abc", 2))))