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

10

如何编写一个高效的算法,用于以下操作:给定一个列表,我们需要输出长度不超过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']]

1
你能使用一个库还是必须编写自己的方法? - Padraic Cunningham
4个回答

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)

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

Documentation:


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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接