Python itertools.combinations提前截止
Python itertools.combinations early cutoff
在下面的代码中,循环产品中从对象 'c' 打印的唯一项目是第一个,尽管 'c' 和 'd' 都包含 3 个项目并且所有'd' 的 3 项已正确迭代。
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 行,但为什么首先会出现这种情况?
问题是c
和d
都是迭代器,第一次通过内循环后,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')
在下面的代码中,循环产品中从对象 'c' 打印的唯一项目是第一个,尽管 'c' 和 'd' 都包含 3 个项目并且所有'd' 的 3 项已正确迭代。
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 行,但为什么首先会出现这种情况?
问题是c
和d
都是迭代器,第一次通过内循环后,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')