生成不重复的字符串列表和锚元素的组合

Generate combinations of a list of strings without repetitions and anchor element

我有一个如下所示的列表:

x = [ 'foo', 'bar', 'alpha' ]

输出应该如下所示。所以 'foo' 需要始终出现在输出

[
 ['foo'],
 ['foo', 'bar']
 ['foo','alpha']
 ['foo','bar','alpha']
]

我查看了 itertools.permutationsitertools.combinations 但两者似乎都不适用于这个用例,因为他们认为值是按位置而不是按数组中的值唯一的。

您可以在 x[1:] 上使用 combinations,改变参数 r:

import itertools

x = ['foo', 'bar', 'alpha']

output = []
for r in range(len(x)):
    output += [['foo'] + list(a) for a in itertools.combinations(x[1:], r)] # attach 'foo' to each item

print(output) # [['foo'], ['foo', 'bar'], ['foo', 'alpha'], ['foo', 'bar', 'alpha']]

在python 3.5+中,可以在循环中使用unpacking来增强可读性:

    output += [['foo', *a] for a in itertools.combinations(x[1:], r)]