我正在尝试使用 生成器 在Python中构建给定集合的子集列表。说我有
set([1, 2, 3])
作为输入,我应该有
[set([1, 2, 3]), set([2, 3]), set([1, 3]), set([3]), set([1, 2]), set([2]), set([1]), set([])]
作为输出。我该如何实现?
最快的方法是使用itertools,尤其是链和组合:
>>> from itertools import chain, combinations >>> i = set([1, 2, 3]) >>> for z in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)): print z () (1,) (2,) (3,) (1, 2) (1, 3) (2, 3) (1, 2, 3) >>>
如果需要生成器,只需使用yield并将元组变成集合:
def powerset_generator(i): for subset in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)): yield set(subset)
然后简单地:
>>> for i in powerset_generator(i): print i set([]) set([1]) set([2]) set([3]) set([1, 2]) set([1, 3]) set([2, 3]) set([1, 2, 3]) >>>