我有一个清单:
[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]]
我怎样才能做到这一点?谢谢!
我有一个清单:
[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]]
我怎样才能做到这一点?谢谢!
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]]
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
它是第一个元素加上所有元素的幂集减去第一个和最后一个元素的组合:
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]]
这个问题与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]]
这是一个生成器。
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]]