在python的两层循环中使用相同的变量时发生了什么? [英] what happened when using the same variable in two layer loops in python?

查看:59
本文介绍了在python的两层循环中使用相同的变量时发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试以下代码:

for i in range(3):
    for i in range(3,5):
        print "inner i: %d"%(i)
    print "outer i: %d"%(i)

输出为:

inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4

我不明白为什么在外循环中 i 是 4 但外循环仍然运行了 3 次.看起来 print "outer i: %d"%(i) 行中的变量 i 是内循环中的 i,但是当转到 for i in range(3) 时,它使用外循环中的 i.

I don't understand why in the outer loop the i is 4 but the outer loop still runs for 3 times. It seems that the the variable i in the print "outer i: %d"%(i) line is the i in the inner loop , but when goes to the for i in range(3) it uses the i in the outer loop.

谁能解释一下?现在对我来说有点困惑.

Anyone can explain this? It's a little confusing to me now.

推荐答案

i,Python 没有块作用域.在每次 for 循环迭代开始时,您将迭代器中的下一个值分配给 i.Python for 循环不像 C/Java for 循环,它们是 foreach 循环.继续直到迭代器耗尽(或者你以某种方式break).for 循环等价于以下 while 循环:

It's the same i, Python doesn't have block scope. At the beginning of each for-loop iteration, you assign the the next value in the iterator to i. Python for-loops aren't like C/Java for-loops, they are foreach loops. The continue until the iterator is exhausted (or you break out somehow). A for-loop is equivalent to the following while-loop:

iterator = iter(my_iterable)
while True:
    try:
        x = next(iterator)
    except StopIteration:
        break
    do_stuff(x)

因此,您的嵌套循环相当于:

So, your nested loop is the equivalent of this:

it1 = iter(range(3))
while True:
    try:
        i = next(it1)
    except StopIteration:
        break

    it2 = iter(range(3, 5))
    while True:
        try:
            i = next(it2)
        except StopIteration:
            break
        print "inner i: %d"%(i)

    print "outer i after: %d"%(i)

注意,一个 C/Java for 循环,例如:

Note, a C/Java for-loop, e.g.:

for (int i = 0; i < stop; i++){
    do_stuff(i);
}

将使用 Python:

Would be in Python:

i = 0
while i < stop:
   do_stuff(i)
   i += 1

也就是说,经典for循环依赖于i,即终止条件依赖于i的值.但是在 for-each 循环中,终止条件取决于迭代器.并且你对主体内的变量做了什么并不重要,在每次迭代开始时,它都会被赋予迭代器的下一个值.

In other words, the classic-for-loop depends on i, that is, the termination condition depends on the value of i. But in a for-each loop, the termination condition depends on the iterator. And it doesn't matter what you do to the variable inside the body, at the beginning of each iteration, it is assigned the next value of the iterator.

这篇关于在python的两层循环中使用相同的变量时发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆