在以下代码中,使用两个元素列表压缩计数。我希望计数器被调用两次,但它被称为三次。为什么呢?
def equivalent_count(start=0, step=1):
"""From python docs for itertools.count."""
n = start
while True:
print('count in loop =', n)
yield n
n += step
c = equivalent_count()
l = [0, 1]
for i, j in zip(c, l):
pass
输出结果为:
count in loop = 0
count in loop = 1
count in loop = 2
zip
状态的文档,"当最短的输入可迭代用尽时,迭代器停止。"
答案 0 :(得分:3)
因为c
的每次迭代都是在l
的等效值之前计算的,所以Python并不知道l
已经用尽了。如果你用生成器替换了l
,你可以看到这个:
def gen_l(lst):
for l in lst:
print 'gen_l called'
yield l
c = equivalent_count()
l = gen_l([0, 1])
for i, j in zip(c, l):
pass
输出:
count in loop = 0
gen_l called
count in loop = 1
gen_l called
count in loop = 2
答案 1 :(得分:2)
交换c
和l
:
for i, j in zip(l, c):
pass
只获得两张照片:
count in loop = 0
count in loop = 1
现在l
已用尽,next(c)
未在您的版本中第三次被调用。