如何列出所有可能的方式来连接字符串列表

问题描述:

我想列出所有可能的方式来连接字符串列表,例如:

输入:

strings = ['hat','bag','cab']

输出:

concatenated = ['hatbag','hatcab','hatbagcab','hatcabbag','baghat','bagcab',
                'baghatcab','bagcabhat','cabhat','cabbag','cabhatbag','cabbaghat']

我已经尝试过为这个简单的3字符串列表使用for循环,但是我无法弄清楚如何使用列表中的许多字符串.

有人可以请帮忙吗?

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?

对于itertools模块而言,这是一个很好的例子.您正在寻找列表原始条目的排列,可以使用itertools.permutations()来获得.这将返回一个元组,因此您必须将它们一起join.最后,您必须告诉permutations()要选择多少个单词,在我们的例子中为至少2个且不超过列表中的单词数".

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."

因为这是Python,所以可以全部用一个列表理解:D

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']

如果列表理解令人困惑,那么这就是我们用for循环编写时的样子.

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']