2012-04-18 41 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)