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

Tom*_*Tom 2 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)}
Run Code Online (Sandbox Code Playgroud)

我想将列表中的所有数字用于组合,但是itertools没有这样做.

所以,我想得到这样的结果:

(0, 0), (0, 1), (0, 1), (1, 0), (1, 0) ...
Run Code Online (Sandbox Code Playgroud)

所以,既然我们有两个0和两个1,我们将有两个(0,1)组合等.

Ami*_*mit 6

集合是没有重复的数据结构.使用清单:

import itertools
a = [0, 0, 1, 1, 2, 2]
combinations = list(itertools.permutations(a, 2))
print(combinations)
Run Code Online (Sandbox Code Playgroud)


abh*_*kdm 5

只需使用itertools.product,它提供了所有可能的组合:

from itertools import product

a = [0, 0, 1, 1, 2, 2]
print (list(product(a, repeat=2)))
Run Code Online (Sandbox Code Playgroud)

得到:

[(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)]
Run Code Online (Sandbox Code Playgroud)