列出长度为n的列表的所有组合(Python)

Mar*_*ska 9 python list

执行以下操作的有效算法是什么:给定列表,我们必须输出长度为n的所有元素组合.假设x = ['a','b','c','d','e']和n = 2.输出应为:

[['a'], ['b'], ['c'], ['d'], ['e'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e'], ['c', 'd'], ['c', 'e'], ['d', 'e']]
Run Code Online (Sandbox Code Playgroud)

Ste*_*ppo 10

你可以使用itertools.combinations和迭代来增加长度:

from itertools import combinations

x = ['a','b','c','d','e']
c = []
n = 2

for i in range(n):
    c.extend(combinations(x, i + 1))

print(c)
Run Code Online (Sandbox Code Playgroud)

或者,使用列表理解:

from itertools import combinations

x = ['a','b','c','d','e']
n = 2
c = [comb for i in range(n) for comb in combinations(x, i + 1)]
print(c)
Run Code Online (Sandbox Code Playgroud)