How to list all posible ways to concatenate a list of strings

二次信任 提交于 2020-06-08 14:06:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!