Python中List的组合项

时间:2013-08-20 12:20:49

标签: python list combinations

我有一个清单:

[0, 1, 2, 3, 4, 5]

我想把除了最后一个之外的所有其他项目合并。 结果应该是一个列表,如下表所示:

[[0], [0,1], [0,2], [0,3], [0,4], [0,1,2], [0,1,3] [0,1, 4], [0,2,3], [0,2,4], [0,3,4], [0,1,2,3], [0,1,2,4], [0, 2,3,4], [0,1,2,3,4]]

我该怎么做? 谢谢!

6 个答案:

答案 0 :(得分:2)

import itertools

a = [0, 1, 2, 3, 4, 5]

base = (a[0],)
items = a[1:-1]
combos = [base + combo for length in range(len(items)+1) for combo in itertools.combinations(items, length)]

# In case it matters that the sublists are lists rather than tuples:
combos = [list(combo) for combo in combos]

print combos
# [[0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 3, 4], [0, 2, 3, 4], [0, 1, 2, 3, 4]]

答案 1 :(得分:1)

首先计算除第一项之外的所有项的power set。搜索“python power set”你会得到几个点击,包括this one。你没有特别提到它,但你可能希望结果按照词法顺序排列,而我选择的实现方式可以让你大部分都在那里。

这将为您提供所需的所有组合,.eg [[],1,...,[1,2,3,4,5]](请注意,这包括空集和整套自己)。现在只需将0添加到每个[[0],[0,1],... [0,1,2,3,4,5]]。

答案 2 :(得分:0)

此问题与powersets

有关
>>> L = [0, 1, 2, 3, 4, 5]
>>> [[L[0]] + [k for j,k in enumerate(L[1:-1]) if i>>j&1] for i in range(1<<(len(L)-2))]
[[0], [0, 1], [0, 2], [0, 1, 2], [0, 3], [0, 1, 3], [0, 2, 3], [0, 1, 2, 3], [0, 4], [0, 1, 4], [0, 2, 4], [0, 1, 2, 4], [0, 3, 4], [0, 1, 3, 4], [0, 2, 3, 4], [0, 1, 2, 3, 4]]

如果您希望它们排序最短到最长:

>>> M = [[L[0]] + [k for j,k in enumerate(L[1:-1]) if i>>j&1] for i in range(1<<(len(L)-2))
>>> sorted(M, key=len)
[[0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 1, 2], [0, 1, 3], [0, 2, 3], [0, 1, 4], [0, 2, 4], [0, 3, 4], [0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 3, 4], [0, 2, 3, 4], [0, 1, 2, 3, 4]]

答案 3 :(得分:0)

它是第一个元素加上所有元素的powerset减去第一个和最后一个元素的组合:

from itertools import chain, combinations

test = [0, 1, 2, 3, 4, 5]

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))


print [test[:1] + list(c) for c in powerset(test[1:-1])]

# [[0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 3, 4], [0, 2, 3, 4], [0, 1, 2, 3, 4]]   

答案 4 :(得分:0)

这是一台发电机。

from itertools import combinations

def custom_combination_gen(l):
    start = [l[0]]
    L = l[1:-1]
    yield start
    for y in range(1, len(L)+1):
        for x in combinations(L, y):
            yield start + list(x)

运行代码:

print list(custom_combination_gen([0,1,2,3,4,5]))
[[0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 3, 4], [0, 2, 3, 4], [0, 1, 2, 3, 4]]

答案 5 :(得分:0)

import itertools
a = [0, 1, 2, 3, 4, 5]
myList = []
myFinalList = []
for i in xrange(0,len(a)-2): myList += list(itertools.combinations(a[1:-1],i))
for item in myList: myFinalList.append(list(item)+[a[0]])
print myFinalList