我知道itertools,但它似乎只能生成没有重复的排列。
例如,我想为 2 个骰子生成所有可能的骰子。所以我需要所有大小为 2 的 [1, 2, 3, 4, 5, 6] 排列,包括重复:(1, 1), (1, 2), (2, 1)...等
如果可能的话,我不想从头开始实现它
最佳答案
您正在寻找 Cartesian Product .
In mathematics, a Cartesian product (or product set) is the direct product of two sets.
在您的情况下,这将是 {1, 2, 3, 4, 5, 6}
x {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)
关于python - 用重复生成排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3099987/