生成器功能不工作python

时间:2017-06-20 22:04:40

标签: python python-2.7 generator

我有一个生成函数,可以生成列表的幂集。我在其中添加了一些打印语句,但是当我运行该项目时,它们都没有打印任何东西。如果我写一个只打印'test'的函数,它就会起作用。有人可以帮忙吗?

def powerSet(items):
    print 'test'
    N = len(items)
    print N
    for i in range(2**N):
        combo = []
        for j in range(N):
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        print combo
        yield combo

list = ['a', 'b', 'c']
powerSet(list)

3 个答案:

答案 0 :(得分:1)

生成器需要迭代才能生成它们的值:

def powerSet(items):
    N = len(items)
    for i in range(2**N):
        combo = []
        for j in range(N):
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        yield combo

list = ['a', 'b', 'c']
for x in powerSet(list):
    print(x)

答案 1 :(得分:1)

powerSet(list)

这将返回生成器,而不是一系列值。为了获得这些价值,我想你想要下面的理解:

>>> powerSet(list)
<generator object powerSet at 0x7f486b44ab90>
>>> [p for p in powerSet(list)]
test
3
[]
['a']
['b']
['a', 'b']
['c']
['a', 'c']
['b', 'c']
['a', 'b', 'c']
[[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]

答案 2 :(得分:1)

做这样的事情:

def powerSet(items):
    N = len(items)
    for i in range(2**N):
        for j in range(N):
            if (i >> j) % 2 == 1
                yield items[j]

>>> list(powerSet(['a', 'b', 'c']))
['a', 'b', 'a', 'b', 'c', 'a', 'c', 'b', 'c', 'a', 'b', 'c']

或者,如果您需要分组元素:

def powerSet(items):
    N = len(items)
    for i in range(2**N):
        combo = []
        for j in range(N):
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        yield combo

>>> list(powerSet(['a', 'b', 'c']))
 [[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]