Python的:一组给定与发电机幂发电机、Python

由网友(爷、来自地狱)分享简介:我想建立一个集在Python是发电机组给定的子集的列表。说我有I am trying to build a list of subsets of a given set in Python with generators. Say I have 设置([1,2,3]) 作为输入,我应该有[组([1,2,3]),集合...

我想建立一个集在Python是发电机组给定的子集的列表。说我有

I am trying to build a list of subsets of a given set in Python with generators. Say I have

设置([1,2,3])

作为输入,我应该有

[组([1,2,3]),集合([2,3]),置([1,3]),集合([3]),集合([1 ,2])中,设置([2]),置([1]),集合([])]

作为输出。我怎样才能做到这一点?

as output. How can I achieve this?

推荐答案

的最快方法是使用itertools,尤其是链和组合:

The fastest way is by using itertools, especially chain and combinations:

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

如果你需要一台发电机只是使用收益,把元组到组:

If you need a generator just use yield and turn tuples into sets:

def powerset_generator(i):
    for subset in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)):
        yield set(subset)

,然后简单:

and then simply:

>>> 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])
>>> 
阅读全文

相关推荐

最新文章