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

时间:2018-12-29 14:58:43

标签: python python-3.x

我有一个字符串列表:['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']

有人可以帮助我找出一种从字符串列表中生成元素的所有排列的方法吗?

2 个答案:

答案 0 :(得分:3)

您可以使用itertools.permutations的第二个参数points=[(633, 312), (630, 351), (623, 389), (611, 426), (594, 462), (573, 495), (548, 525), (519, 552), (488, 575), (453, 594), (417, 608), (379, 618), (340, 623), (301, 623), (262, 618), (224, 608), (188, 594), (153, 575), (122, 552), (93, 525), (68, 495), (47, 462), (30, 426), (18, 389), (11, 351), (9, 311), (11, 272), (18, 234), (30, 197), (47, 161), (68, 128), (93, 98), (122, 71), (153, 48), (188, 29), (224, 15), (262, 5), (301, 0), (340, 0), (379, 5), (417, 15), (453, 29), (488, 48), (519, 71), (548, 98), (573, 128), (594, 161), (611, 197), (623, 234), (630, 272)] mask1 = prepare_mask(points, image_gray, 0) mask2 = prepare_mask(points, image_gray, 1) histogram1 = compute_histogram(mask1, image_gray) histogram2 = compute_histogram(mask2, image_gray) dist=f_dist(histogram1,histogram2) 来获取所需的迭代器:

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

答案 1 :(得分:2)

以下解决方案可能满足您的需求。您的解决方案使用itertools.combinations排列组合之间的主要区别在于组合的顺序无关紧要,例如'redblue'和{ {1}}不会是唯一的。

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