简体   繁体   English

生成字符串列表的所有排列

[英]Generating all permutations of a list of strings

I have a list of strings: ['red','blue','pink'] and I'm trying to generate a list of all permutations of the elements of the given list as follows:我有一个字符串列表: ['red','blue','pink']并且我正在尝试生成给定列表元素的所有排列的列表,如下所示:

['red', 'redblue', 'redbluepink', 'redpinkblue',
 'blue', 'bluered', 'bluepink', 'blueredpink', 'bluepinkred',
 'pink', 'pinkred', 'pinkblue', 'pinkredblue', 'pinkbluered']

I have managed to write the following code to generate all the forward permutations of the elements of a list:我设法编写了以下代码来生成列表元素的所有前向排列:

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

However, this code only manages to generate all the forward permutations:但是,此代码只能生成所有前向排列:

['red', 'redblue', 'redbluepink', 'blue', 'bluepink', 'pink']

Could anyone help me figure out a way to generate all the permutations of the elements from a list of strings?谁能帮我找出一种方法来从字符串列表中生成元素的所有排列?

You can use the second parameter to itertools.permutations , r to get the iterator you want:您可以使用itertools.permutations的第二个参数, r来获取您想要的迭代器:

from itertools import permutations

def all_permutations(x):
    for r in range(1, len(x) + 1):
        yield from permutations(x, r)

To combine the result:要合并结果:

[''.join(s) for s in all_permutations(['red', 'blue', 'pink'])]

Or或者

map(''.join, all_permutations(['red', 'blue', 'pink']))

This will give you an order different from the one in the question.这将为您提供与问题中不同的顺序。 You can impose the order you want by sorting according to the index in your original list:您可以通过根据原始列表中的索引进行排序来强加您想要的顺序:

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]

The following solution may meet your needs.以下解决方案可能会满足您的需求。 Your solution is using itertools.combinations , and the key difference between permutations and combinations is that order does not matter in combinations, such that 'redblue' and 'bluered' would not be unique.您的解决方案是使用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))

Result:结果:

['red', 'blue', 'pink', 'redblue', 'redpink', 'bluered', 'bluepink', 'pinkred', 'pinkblue', 'redbluepink', 'redpinkblue', 'blueredpink', 'bluepinkred', 'pinkredblue', 'pinkbluered']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM