如何列出所有可能的方式来连接字符串列表 [英] How to list all posible ways to concatenate a list of strings

查看:98
本文介绍了如何列出所有可能的方式来连接字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

输入:

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

这篇关于如何列出所有可能的方式来连接字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆