我有一个数字列表:[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)组合等。
答案 0 :(得分:5)
集合是没有重复的数据结构。使用清单:
import itertools
a = [0, 0, 1, 1, 2, 2]
combinations = list(itertools.permutations(a, 2))
print(combinations)
答案 1 :(得分:5)
只需使用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)]