简体   繁体   中英

How do I get combinations of a list of words in python

I am trying to make a script that if I gave it a list of words such as ('1', '2', '3') it would give me:

1 12 13 123 232 2 21 23 213 231 3 31 32 31 32 312 321

I have tried itertools but I couldn't figure it out How can I do this?

Thankyou

You need a variant of the powerset recipe from itertools using permutations instead of combinations:

from itertools import permutations, chain

def powerperm(iterable):
    s = list(iterable)
    return chain.from_iterable(permutations(s, r) for r in range(1, len(s)+1))

inp = ('1', '2', '3')

out = list(map(''.join, powerperm(inp)))
out

output: ['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']

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