本文介绍了通过重复生成排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我了解itertools,但似乎只能生成排列而不能重复.
I know about itertools, but it seems it can only generate permutations without repetitions.
例如,我想为2个骰子生成所有可能的骰子骰.因此,我需要大小为2的[1、2、3、4、5、6]的所有排列,包括重复:(1、1),(1、2),(2、1)...等等
For example, I'd like to generate all possible dice rolls for 2 dice. So I need all permutations of size 2 of [1, 2, 3, 4, 5, 6] including repetitions: (1, 1), (1, 2), (2, 1)... etc
如果可能的话,我不想从头开始实现
If possible I don't want to implement this from scratch
推荐答案
您正在寻找笛卡尔积.
在您的情况下,这将是{1, 2, 3, 4, 5, 6}
x {1, 2, 3, 4, 5, 6}
. itertools
可以为您提供帮助:
In your case, this would be {1, 2, 3, 4, 5, 6}
x {1, 2, 3, 4, 5, 6}
.itertools
can help you there:
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)]
要随机掷骰子(以完全无效的方式):
To get a random dice roll (in a totally inefficient way):
import random
random.choice([p for p in itertools.product(x, repeat=2)])
(6, 3)
这篇关于通过重复生成排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!