我想知道如何从列表中获得所有可能的组合。
list1 = [1,5,3]
这应该返回:
ans = [1,5,3,15,13,51,53,31,35,153,135,315,351,531,513]
感谢回复
亚当
答案 0 :(得分:2)
您需要permutations,而不是combinations:
from itertools import permutations
list1 = [1,5,3]
n = len(list1)
print([int("".join(map(str, ints))) for i in range(n)
for ints in permutations(list1, i + 1)])
# [1, 5, 3, 15, 13, 51, 53, 31, 35, 153, 135, 513, 531, 315, 351]
答案 1 :(得分:0)
import itertools
import operator
import numpy as np
a=[1,2,3]
[list(i) for i in reduce(operator.add,[list(itertools.combinations(a,i)) for i in range(1,len(a)+1)])]
然后结果是
[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
如果您希望它具有您在问题中列出的确切格式,则可以执行
import itertools
import operator
import numpy as np
a=[1,2,3]
a=[str(i) for i in a]
[int(''.join(list(i))) for i in reduce(operator.add,[list(itertools.combinations(a,i)) for i in range(1,len(a)+1)])]
结果是
[1, 2, 3, 12, 13, 23, 123]
答案 2 :(得分:0)
蛮力:
import random
list1 = [1,5,3]
brute = 1000
combos = []
for i in range(brute):
random.shuffle(list1)
z = ''.join(str(x) for x in list1)
for i in range(len(list1)):
combos.append(int(z[i:]))
combos = sorted(list(set(combos)))
print combos
>>>[1, 3, 5, 13, 15, 31, 35, 51, 53, 135, 153, 315, 351, 513, 531]