2017-10-19 79 views
0

在以下代碼中,雖然'c'和'd'都包含3個項目和全部3個項目,但是從循環產品中的對象'c'打印的唯一項目是第一個項目'd'正確迭代。Python itertools.combinations early cutoff

from itertools import combinations 

c,d = combinations(map(str, range(3)),2), combinations(map(str, range(3)),2) 
for x in c: 
for y in d: 
    print(x,y) 

列表生成列表解決這個問題,打印9行,但爲什麼這首先發生?

回答

2

問題是,cd都是迭代器,並在第一次通過內循環後,d已用盡。解決這個問題的最簡單的方法就是做:

from itertools import combinations, product 

c = combinations(map(str, range(3)),2) 
d = combinations(map(str, range(3)),2) 

for x, y in product(c, d): 
    print(x,y) 

這將產生:

('0', '1') ('0', '1') 
('0', '1') ('0', '2') 
('0', '1') ('1', '2') 
('0', '2') ('0', '1') 
('0', '2') ('0', '2') 
('0', '2') ('1', '2') 
('1', '2') ('0', '1') 
('1', '2') ('0', '2') 
('1', '2') ('1', '2') 
+0

它是這麼簡單!我一直認爲第一臺發電機出現了問題。 +1爲基於itertools.product的方法。 –

相關問題