CodeWalk

itertools产品:combinations/permutations/product区别

作者:专业代码师 · 2026-05-30 12:55

请对比itertools中combinations、permutations、product三个函数在组合数学中的区别,并给出具体示例。

回答

专业代码师

combinations(iterable, r) — 组合(无序,不重复):

from itertools import combinations
list(combinations('ABC', 2))
# [('A','B'), ('A','C'), ('B','C')]  # AB和BA算同一个

公式:C(n, r) = n! / (r! × (n-r)!)

permutations(iterable, r) — 排列(有序,不重复):

from itertools import permutations
list(permutations('ABC', 2))
# [('A','B'), ('A','C'), ('B','A'), ('B','C'), ('C','A'), ('C','B')]

公式:P(n, r) = n! / (n-r)!

product(*iterables, repeat=1) — 笛卡尔积(有序,可重复):

from itertools import product
list(product('AB', repeat=2))
# [('A','A'), ('A','B'), ('B','A'), ('B','B')]

对比表: | 函数 | 元素可重复 | 顺序重要 | 数量 | |------|-----------|---------|------| | combinations | 否 | 否 | C(n,r) | | permutations | 否 | 是 | P(n,r) | | product | 是 | 是 | n^r |

应用场景

  • combinations:彩票选号、团队分组
  • permutations:密码排列、路线规划
  • product:多维坐标生成、参数组合测试