列出长度不超过n的所有组合(Python)

10 投票
4 回答
6541 浏览
提问于 2025-04-18 14:52

我们想要一个高效的方法来完成以下任务:给定一个列表,我们需要输出所有元素组合,组合的长度最多为 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']]

4 个回答

1

因为你在寻找一个算法,而不是一个工具……这个可以生成所有可能的独特组合。

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

outList = []
for i in range(0,len(x)):
    outEleList = []
    outEleList.append(x[i])
    outList.append(outEleList)
    for c in range(i,len(x)):
        out = []
        out.append(x[i])
        out.append(x[c])
        outList.append(out)

print outList
2

使用 itertools.combinations

>>> x = ['a','b','c','d','e']
>>> n = 2
>>> import itertools
>>> [list(comb) for i in range(1, n+1) for comb in itertools.combinations(x, i)]
[['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']]
3

代码:

x = ['a', 'b', 'c', 'd', 'e']
result = []

for length in range(1,3):
    result.extend(itertools.combinations(x, length))

print result

输出:

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

文档:

13

你可以使用 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)

或者,你也可以用一种叫做列表推导式的方法来实现:

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)

撰写回答