1

我有一个清单:

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

我怎样才能做到这一点?谢谢!

4

6 回答 6

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]]
于 2013-08-20T12:30:55.987 回答
1

首先计算除第一项之外的所有项的幂集。搜索“python power set”你会得到几个点击,包括这个。您没有特别提到它,但您可能希望按字典顺序排列结果,而我选择的实现可以帮助您实现大部分目标。

这将为您提供所需的所有组合,例如 [[], 1 , ..., [1,2,3,4,5]] (注意这包括空集和整个集本身)。现在只需在每个前面加上 0 就可以得到 [[0],[0,1],...[0,1,2,3,4,5]]。

于 2013-08-20T12:34:35.547 回答
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
于 2013-08-20T13:09:58.043 回答
0

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

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]]   
于 2013-08-20T12:40:19.540 回答
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]]
于 2013-08-20T12:30:31.733 回答
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]]
于 2013-08-20T12:41:44.837 回答