2017-06-20 70 views
1

我有一个发电机功能,产生列表的功率集。我在里面放了一些打印语句,但是当我运行这个项目时,他们都没有打印任何东西。如果我编写一个只打印“测试”的函数,它可以工作。有人可以帮忙吗?发电机功能不工作python

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

迭代powerSet(list) – haifzhan

+3

在你自己的代码中使用像'list'这样的内建名称作为变量是一个非常糟糕的主意。像这样消耗一个生成器的自然方式是'list(generator(whatever))',但是因为你已经反弹了名字'list',那实际上并不能正常工作。 – Blckknght

回答

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

做这样的事情:

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