我怎样才能在python 3.x中创建一个给定列表的所有子集的列表?给定的列表类似[1,2,3]并且我想要一个类似的输出
[1,2,3]
[[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3],[]]
ego6inou1#
您可以使用itertools.combinations来获得以下组合:
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]]
nhaq1z212#
这个问题实际上是问幂集,这里有另一种生成它的方法:(不使用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 >>> list(more_itertools.powerset(L)) [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] >>>
mhd8tkvw3#
**如果只使用more_intertools中的一个函数,则无需安装more_intertools。**您可以查看itertools文档中的Itertools Recipes,它包含以下配方:
more_intertools
itertools
from itertools import chain, combinations 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))
实际上,more_itertools.powerset具有完全相同的实现。
more_itertools.powerset
ecr0jaav4#
我试过了,没有递归,结果很成功。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
4条答案
按热度按时间ego6inou1#
您可以使用
itertools.combinations
来获得以下组合:结合列表理解,你会得到你想要的:
nhaq1z212#
这个问题实际上是问幂集,这里有另一种生成它的方法:(不使用itertools.combinations())
或者,您可以使用此第三方库more_itertools:powerset(这个名称恰当地反映了它的用途)。
mhd8tkvw3#
**如果只使用
more_intertools
中的一个函数,则无需安装more_intertools
。**您可以查看itertools
文档中的Itertools Recipes,它包含以下配方:实际上,
more_itertools.powerset
具有完全相同的实现。ecr0jaav4#
我试过了,没有递归,结果很成功。
A是列表,K是每个子集的长度