Python 了解与发电机相关的输出
我不清楚为什么下面代码的输出是5而不是6:Python 了解与发电机相关的输出,python,generator,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+
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
def计数器(尺寸):
cur=1
cur行Total=Total+x+y
执行两次
x==1
和y==1
:Total=0+1+1
soTotal==2
x==1
和y==2
:Total=2+1+2
soTotal==5
然后,由于c2
已经运行,内部循环结束。外部循环使用x==2
进行另一次迭代,但是c2
中没有任何剩余内容,因此内部for循环不再被输入