问题
I want to list all possible ways to concatenate a list of strings, example:
Input:
strings = ['hat','bag','cab']
Output:
concatenated = ['hatbag','hatcab','hatbagcab','hatcabbag','baghat','bagcab',
'baghatcab','bagcabhat','cabhat','cabbag','cabhatbag','cabbaghat']
I've tried using for loops for this simple 3 string list, but I can't figure out how to do it with many strings in the list. Can someone please help?
回答1:
This is a great case for the itertools
module. You're looking for permutations of the original entries of the list, which you can get with itertools.permutations()
. This returns a tuple, so you'll have to join
them together. Finally, you have to tell permutations()
how many words to choose, which in our case is "at least 2 and not more than the number of words in the list."
Since this is Python, it can all be done with one list comprehension :D
>>> from itertools import permutations
>>> strings = ['hat','bag','cab']
>>> [''.join(s) for i in range(2,len(strings)+1) for s in permutations(strings,i)]
['hatbag',
'hatcab',
'baghat',
'bagcab',
'cabhat',
'cabbag',
'hatbagcab',
'hatcabbag',
'baghatcab',
'bagcabhat',
'cabhatbag',
'cabbaghat']
In case the list comprehension is confusing, this is what it would look like if we wrote it with for
loops.
>>> from itertools import permutations
>>> strings = ['hat','bag','cab']
>>> concats = []
>>> for i in range(2, len(strings)+1):
... for s in permutations(strings, i):
... concats.append(''.join(s))
...
>>> concats
['hatbag',
'hatcab',
'baghat',
'bagcab',
'cabhat',
'cabbag',
'hatbagcab',
'hatcabbag',
'baghatcab',
'bagcabhat',
'cabhatbag',
'cabbaghat']
来源:https://stackoverflow.com/questions/61881904/how-to-list-all-posible-ways-to-concatenate-a-list-of-strings