简体   繁体   English

如何获得列表整数的所有可能组合?

[英]How to get every possible combination of list integers?

I have a list L = [3, 4, 1, 5, 9] and I want to get every possible numbers that can be made by using those numbers present in list L .我有一个列表L = [3, 4, 1, 5, 9]并且我想获得所有可能的数字,这些数字可以通过使用列表L存在的那些数字来制作。 I mean, I want to get an output like this: [3, 4, 1, 5, 9, 34, . . . . , 91, 953, ... ,41593, ... etc.]我的意思是,我想得到这样的输出: [3, 4, 1, 5, 9, 34, . . . . , 91, 953, ... ,41593, ... etc.] [3, 4, 1, 5, 9, 34, . . . . , 91, 953, ... ,41593, ... etc.] [3, 4, 1, 5, 9, 34, . . . . , 91, 953, ... ,41593, ... etc.] I am using this code: [3, 4, 1, 5, 9, 34, . . . . , 91, 953, ... ,41593, ... etc.]我正在使用以下代码:

from itertools import combinations
possible_numbers = []

output = (sum([list(map(list, combinations(L, i))) for i in range(len(L) + 1)], []))
output.pop(0)

for x in output:
    strings = [str(integer) for integer in x]
    a_string = "".join(strings)
    possible_numbers.append(int(a_string))
    print(output)

But I am getting this type of output:但我得到了这种类型的输出:

[3,4,1,5,9,34,31,35,39, 4145,49,15,19,59,341,345,349,315,319,359,415,419,459,159,3415,3419,3459,3159,4159,34159]

Clearly this is not what I want, because there can be more possible combinations formed with list L .显然这不是我想要的,因为列表L可以形成更多可能的组合。 Can anyone please help.任何人都可以请帮忙。

Try itertools.permutations :尝试itertools.permutations

from itertools import permutations

L = [3, 4, 1, 5, 9]

for i in range(1, len(L) + 1):
    for p in permutations(L, i):
        print(int("".join(map(str, p))))

Prints:印刷:

3
4
1
5
9
34
31
35

...

95431
95413
95134
95143

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM