Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python查找具有设定长度的所有可能的数字组合_Python_Algorithm_Combinations - Fatal编程技术网

python查找具有设定长度的所有可能的数字组合

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)} 我想用列表中的所有数字来组

我有一个数字列表:[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)}
我想用列表中的所有数字来组合,但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)]
集合中不能有重复项
——这是
集合的一个要点