2012-04-18 40 views
1

itertools函数没有错误,但它在完成后也不会打印任何内容。 我的代码是:问题打印组合

def comb(iterable, r): 
    pool = tuple(iterable) 
    n = len(pool) 
    for indices in permutations(range(n), r): 
     if sorted(indices) == list(indices): 
      print (indices) 
      yield tuple(pool[i] for i in indices) 

我包括print语句,但它并不打印计算的总组合。

+0

为什么要创建一个整数列表,只要输入数据,产生它们的排列,使用每个排列作为一对索引到原始并产生结果?噢,因为你想过滤他们订购?这就是'itertools.combinations'的用途;它直接取代你的整个功能。 – 2012-04-18 06:30:50

回答

2

您需要在发电机的工作原理阅读起来。当您致电comb()时,它将返回一个生成器对象。然后,您需要对生成器对象执行一些操作,以获取从其返回的对象。

from itertools import permutations 

lst = range(4) 
result = list(comb(lst, 2)) # output of print statement is now shown 

print(result) # prints: [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] 

comb()返回一个生成器对象。然后,list()迭代它并收集列表中的值。在迭代时,您的打印语句会触发。

+0

我得到这个错误:对于排列(范围(n),r)中的索引: NameError:全局名称'permutations'未定义 – 2012-04-18 03:06:14

+0

您需要有一个'import'语句。我在我的例子中添加了一个。 – steveha 2012-04-18 03:07:34

+0

感谢这有助于! – 2012-04-18 03:10:26

1

它返回一个generator对象。如果你迭代它,你会看到打印。例如:

for x in comb(range(3),2): 
    print "Printing here:", x 

为您提供:

(0, 1) # due to print statement inside your function 
Printing here: (0, 1) 
(0, 2) # due to print statement inside your function 
Printing here: (0, 2) 
(1, 2) # due to print statement inside your function 
Printing here: (1, 2) 

所以,如果你只是想打印由线组合线,取出自己的函数中打印语句,只是它转换成一个列表或者iterate通过它。您可以通过行打印这些行:

print "\n".join(map(str,comb(range(4),3))) 

给你

(0, 1, 2) 
(0, 1, 3) 
(0, 2, 3) 
(1, 2, 3)