在Python3.x中创建给定列表的所有子集的列表

在Python3.x中创建给定列表的所有子集的列表,python,list,python-3.x,Python,List,Python 3.x,如何在Python3.x中创建给定列表的所有子集的列表? 给出的列表类似于[1,2,3],我希望输出类似于 [[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3],[]] 您可以使用获取以下组合: >>> import itertools >>> xs = [1, 2, 3] >>> itertools.combinations(xs, 2) # returns an iterator <itertools.

如何在Python3.x中创建给定列表的所有子集的列表? 给出的列表类似于
[1,2,3]
,我希望输出类似于

[[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3],[]]
您可以使用获取以下组合:

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

我试过这个。没有递归。结果很成功

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

问题真的是要问powerset。下面是生成它的另一种方法: (不带itertools.compositions())

或者您可以使用更多的\u 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)]
>>> 
>>导入更多工具
>>>更多itertools.powerset(L)
>>>列表(更多itertools.powerset(L))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>> 

如果不使用这些组合,是否还有其他组合alternative@RISHABHBANSAL,据我所知,使用
itertools.compositions
是最简单的。没有它,您需要生成一个递归函数。
>>> 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]]
>>> 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)]
>>>