执行以下操作的有效算法是什么: 给定一个列表,我们必须输出长度为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']]
答案 0 :(得分: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)
或者,使用列表理解:
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)
答案 1 :(得分: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')]
答案 2 :(得分:2)
>>> 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 :(得分:0)
由于您正在寻找算法而不是工具...这会提供所有可能的独特组合。
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