了解与发电机相关的输出

2024-04-23 08:48:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我不清楚为什么下面代码的输出是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

Tags: the代码inforsizedefcountertotal
1条回答
网友
1楼 · 发布于 2024-04-23 08:48:51

Total = Total + x + y

  • x==1和{}:{}所以{}
  • x==1和{}:{}所以{}

然后,由于c2已经运行了它的过程,内部循环结束。外部循环使用x==2进行另一次迭代,但是c2中什么都没有了,因此内部for循环不再被输入

相关问题 更多 >