简体   繁体   中英

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 . 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.] I am using this code:

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 . Can anyone please help.

Try 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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