如何在python 3.x中创建给定列表的所有子集的列表?
给出的列表如[1,2,3]
,我想要一个像
[[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3],[]]
答案 0 :(得分:5)
您可以使用itertools.combinations
获取组合:
>>> import itertools
>>> xs = [1, 2, 3]
>>> itertools.combinations(xs, 2) # returns an iterator
<itertools.combinations object at 0x7f88f838ff48>
>>> list(itertools.combinations(xs, 2)) # yields 2-length subsequences
[(1, 2), (1, 3), (2, 3)]
>>> for i in range(0, len(xs) + 1): # to get all lengths: 0 to 3
... for subset in itertools.combinations(xs, i):
... print(list(subset))
...
[]
[1]
[2]
[3]
[1, 2]
[1, 3]
[2, 3]
[1, 2, 3]
结合列表理解,你会得到你想要的东西:
>>> [list(subset) for i in range(0, len(xs) + 1)
for subset in itertools.combinations(xs, i)]
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
答案 1 :(得分:1)
问题实际上是要询问功率集。这是生成它的另一种方法: (没有itertools.combinations())
>>> L = [1, 2, 3]
>>> res = [[]]
>>> for e in L:
res += [sub + [e] for sub in res]
>>> res
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
或者您也可以使用more_itertools.powerset()生成它:
>>> import more_itertools
>>> more_itertools.powerset(L)
<itertools.chain object at 0x00186F28>
>>> list(more_itertools.powerset(L))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>>
答案 2 :(得分:0)
我尝试过了。没有递归。顺利完成。
A是列表,K是每个子集的长度
def subsets(A,K):
sets = []
for j in range(len(A)-K+1):
mySet = []
for i in range(j,K+j):
mySet.append(A[i])
sets.append(mySet)
return sets