python查找具有设定长度的所有可能的数字组合
我有一个数字列表:[0,0,1,1,2,2] 我想要2个数字的所有组合,我尝试使用itertools:python查找具有设定长度的所有可能的数字组合,python,algorithm,combinations,Python,Algorithm,Combinations,我有一个数字列表:[0,0,1,1,2,2] 我想要2个数字的所有组合,我尝试使用itertools: import itertools a = [0, 0, 1, 1, 2, 2] combinations = set(itertools.permutations(a, 2)) print(combinations) # {(0, 1), (1, 2), (0, 0), (2, 1), (2, 0), (1, 1), (2, 2), (1, 0), (0, 2)} 我想用列表中的所有数字来组
import itertools
a = [0, 0, 1, 1, 2, 2]
combinations = set(itertools.permutations(a, 2))
print(combinations)
# {(0, 1), (1, 2), (0, 0), (2, 1), (2, 0), (1, 1), (2, 2), (1, 0), (0, 2)}
我想用列表中的所有数字来组合,但itertools没有做到
所以,我想得到这样的结果:
(0, 0), (0, 1), (0, 1), (1, 0), (1, 0) ...
因此,由于我们有两个0和两个1,我们将有两个(0,1)组合等等。集合是一个没有重复项的数据结构。使用列表:
import itertools
a = [0, 0, 1, 1, 2, 2]
combinations = list(itertools.permutations(a, 2))
print(combinations)
只需使用
itertools.product
,它提供了所有可能的组合:
from itertools import product
a = [0, 0, 1, 1, 2, 2]
print (list(product(a, repeat=2)))
给出:
[(0, 0), (0, 0), (0, 1), (0, 1),
(0, 2), (0, 2), (0, 0), (0, 0),
(0, 1), (0, 1), (0, 2), (0, 2),
(1, 0), (1, 0), (1, 1), (1, 1),
(1, 2), (1, 2), (1, 0), (1, 0),
(1, 1), (1, 1), (1, 2), (1, 2),
(2, 0), (2, 0), (2, 1), (2, 1),
(2, 2), (2, 2), (2, 0), (2, 0),
(2, 1), (2, 1), (2, 2), (2, 2)]
在集合中不能有重复项
——这是集合的一个要点