[英]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.