我有一个列表,例如
x=[1,2,4,5,8,9]
我想要实现的是从列表中获取包含4位数字组合的列表。例如:输出应为
[1,2,4,5]
[2,3,4,8]
.....
[1,3,5,8]
....
因此,我相信它将是4^6
解决方案。我尝试过itertools组合没有成功
答案 0 :(得分:4)
Itertools实际上是答案,因为您想要的是长度为N的排列。
import itertools as it
x=[1,2,4,5,8,9]
print(list(it.permutations(x, 4)))
答案 1 :(得分:1)
如果顺序无关紧要,请使用itertools.combinations
:
from itertools import combinations
x=[1,2,4,5,8,9]
for c in combinations(x, 4):
print(c)
这将输出:
(1, 2, 4, 5)
(1, 2, 4, 8)
(1, 2, 4, 9)
(1, 2, 5, 8)
(1, 2, 5, 9)
(1, 2, 8, 9)
(1, 4, 5, 8)
(1, 4, 5, 9)
(1, 4, 8, 9)
(1, 5, 8, 9)
(2, 4, 5, 8)
(2, 4, 5, 9)
(2, 4, 8, 9)
(2, 5, 8, 9)
(4, 5, 8, 9)
答案 2 :(得分:0)
您可以尝试以下方法:
from itertools import combinations
x=[1,2,4,5,8,9]
comb = list(map(list, itertools.combinations(x, 4)))
print(comb)
[[1, 2, 4, 5], [1, 2, 4, 8], [1, 2, 4, 9], [1, 2, 5, 8], [1, 2, 5, 9], [1, 2, 8, 9], [1, 4, 5, 8], [1, 4, 5, 9], [1, 4, 8, 9], [1, 5, 8, 9], [2, 4, 5, 8], [2, 4, 5, 9], [2, 4, 8, 9], [2, 5, 8, 9], [4, 5, 8, 9]]