了解与生成器关联的输出

时间:2014-12-10 02:12:56

标签: python generator

我不清楚为什么以下代码的输出是5而不是6:

def counter_gen(size):
    cur = 1
    while cur <= size:
        yield cur
        cur = cur + 1

c1 = counter_gen(2)
c2 = counter_gen(2)

Total = 0
for x in c1:
    for y in c2:
        Total = Total + x + y # Isn't this 0+1+1 in the first iteration and then 2+2+2 in the 2nd iteration, hence giving 6?

print Total

1 个答案:

答案 0 :(得分:3)

使用

执行两行Total = Total + x + y
  • x==1y==1Total = 0 + 1 + 1所以Total==2
  • x==1y==2Total = 2 + 1 + 2所以Total==5

然后,由于c2已经运行,内循环结束。外部循环使用x==2进行另一次迭代,但c2中没有任何内容,因此永远不再输入内部for循环。

相关问题