如何从列表中获取“带重复的排列”(列表的笛卡尔积)?
假设我有一个列表 die_faces = [1, 2, 3, 4, 5, 6]
,这个列表代表了一个六面骰子的六个面。我想要生成掷两个骰子时可能出现的所有36种结果,比如 (1, 1)
、(1, 2)
、(2, 1)
等等。如果我尝试使用 itertools
这个标准库里的 permutations
函数:
>>> import itertools
>>> die_faces = [1, 2, 3, 4, 5, 6]
>>> list(itertools.permutations(die_faces, 2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5)]
结果只有30种,缺少了两个骰子出现相同数字的情况。看起来这个函数只生成了不重复的排列。那我该怎么解决这个问题呢?
6 个回答
14
在Python 2.7和3.1版本中,有一个叫做 itertools.combinations_with_replacement
的函数:
>>> list(itertools.combinations_with_replacement([1, 2, 3, 4, 5, 6], 2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 2), (2, 3), (2, 4),
(2, 5), (2, 6), (3, 3), (3, 4), (3, 5), (3, 6), (4, 4), (4, 5), (4, 6),
(5, 5), (5, 6), (6, 6)]
219
你在找的是笛卡尔积。
在数学中,笛卡尔积(或者叫乘积集合)是两个集合的直接乘积。
在你的例子中,这就是 {1, 2, 3, 4, 5, 6}
和 {1, 2, 3, 4, 5, 6}
的组合。
itertools
可以帮你实现这个:
import itertools
x = [1, 2, 3, 4, 5, 6]
[p for p in itertools.product(x, repeat=2)]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3),
(2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6),
(4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3),
(5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]
如果你想要得到一个随机的骰子点数(用一种非常低效的方法):
import random
random.choice([p for p in itertools.product(x, repeat=2)])
(6, 3)