[英]Generating all permutations of a list of strings
我有一个字符串列表: ['red','blue','pink']
并且我正在尝试生成给定列表元素的所有排列的列表,如下所示:
['red', 'redblue', 'redbluepink', 'redpinkblue',
'blue', 'bluered', 'bluepink', 'blueredpink', 'bluepinkred',
'pink', 'pinkred', 'pinkblue', 'pinkredblue', 'pinkbluered']
我设法编写了以下代码来生成列表元素的所有前向排列:
from itertools import combinations
def all_permutations(list_of_strings):
results = [''.join(list_of_strings[i:j]) for i, j in combinations(range(len(list_of_strings) + 1), 2)]
return results
print(all_permutations(['red','blue','pink']))
但是,此代码只能生成所有前向排列:
['red', 'redblue', 'redbluepink', 'blue', 'bluepink', 'pink']
谁能帮我找出一种方法来从字符串列表中生成元素的所有排列?
您可以使用itertools.permutations
的第二个参数, r
来获取您想要的迭代器:
from itertools import permutations
def all_permutations(x):
for r in range(1, len(x) + 1):
yield from permutations(x, r)
要合并结果:
[''.join(s) for s in all_permutations(['red', 'blue', 'pink'])]
或者
map(''.join, all_permutations(['red', 'blue', 'pink']))
这将为您提供与问题中不同的顺序。 您可以通过根据原始列表中的索引进行排序来强加您想要的顺序:
items = ['red', 'blue', 'pink']
index = {k: i for i, k in enumerate(items)}
all_items = sorted(all_permutations(items), key=lambda item: tuple(index[x] for x in item))
all_items = [''.join(item) for item in all_items]
以下解决方案可能会满足您的需求。 您的解决方案是使用itertools.combinations
和排列组合之间的关键区别在于,为了无所谓的组合,使得'redblue'
和'bluered'
不会是唯一的。
from itertools import permutations
def all_permutations(l):
o = []
for x in range(1, len(l) + 1):
o.extend([''.join(p) for p in list(permutations(l, x))])
return o
colors = ['red', 'blue', 'pink']
print(all_permutations(colors))
结果:
['red', 'blue', 'pink', 'redblue', 'redpink', 'bluered', 'bluepink', 'pinkred', 'pinkblue', 'redbluepink', 'redpinkblue', 'blueredpink', 'bluepinkred', 'pinkredblue', 'pinkbluered']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.