[英]Python. Find all possible combinations of numbers with set length
我有一个数字列表:[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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.