Python itertools.combinations early cutoff

问题描述:

在以下代码中,虽然'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行,但为什么这首先发生?

问题是,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的方法。 –