在下面的代码中,从环积中的对象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行,但是为什么首先会出现这种情况呢?
发布于 2017-10-19 13:49:54
问题是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')https://stackoverflow.com/questions/46831353
复制相似问题