不理解 Python 中的嵌套 For 循环

Don't understand nested For Loop in Python

我不明白下面代码的第二个 for 循环中的 i 是如何工作的。

di = [96, 15, 33, 87]
for i in range(len(di)):
    total = di[i]
    for j in range(i+1,len(di)):
        print(i)
0
0
0
1
1
2

为什么输出是0,0,0,1,1,2。第二个 for 循环中的 i 如何受到第一个循环的影响?有什么遗传吗?原谅这里的新手。

在编程语言中,变量可在一个范围内使用。当你用一个新变量开始 for 循环时,它就可以使用,直到你结束它。

当您开始学习之旅时 python,真正好的做法之一是阅读官方文档。 https://docs.python.org/3/tutorial/controlflow.html

为了帮助您理解,试试这个:

di = [96, 15, 33, 87]
for i in range(len(di)):
    print("first loop, i =", i)
    total = di[i]
    for j in range(i+1,len(di)):
        print("second loop, j =", j)
        print("second loop, i =", i)

两个循环中的 i 相同。每次外循环运行时,它都会运行内循环,直到 "for" 语句完成。

len(di) 是 4。所以循环

for i in range(len(di)):

会重复4次。由于 range 的工作方式(从下限(如果未指定,默认情况下为 0)到上限以下的 1),i 在第一次重复时将是 01 在第二次重复中,依此类推。要计算出 range(x, y) 生成了多少对象,在这种情况下,for i in range(x, y) 将重复多少次,您可以简单地执行 number of repetitions = y - x。所以在这种情况下:len(di) - 0 (default lower bound) = 4.

循环

for j in range(i+1, len(di)):
    print(i)

将重复 print(i) 命令 len(di) - (i + 1) 次。请记住,i 是由外循环定义的。所以,在

的第一个循环中
for i in range(len(di)):

i 等于 0,所以 print(i) 命令将被执行 4 - (0+1) = 3 次 - 它会打印 i(=0) 3 次。第二次循环,i等于1,所以会打印2次,以此类推。所以这是发生了什么,格式化为代码以提高可读性:

First outer loop: 
i = 0
total = di[i] = di[0] = 96
--> first inner loop of first outer loop:
    j = i + 1 = 1
    i is printed -> prints 0

    second inner loop of first outer loop:
    j = j+1 = 2
    i is printed -> prints 0 again

    third inner loop of first outer loop:
    j = j+1 = 3 --> since len(di) = 4, the upper bound of range(i+1, len(di)) is reached, so this is the last Repetition
    i is printed -> prints 0 again

Second outer loop:
i = 1
total = di[1] = 15
--> first inner loop of second outer loop:
    j = i+1 = 2
    i is printed -> prints 1

    second inner loop of second outer loop:
    j = i+1 = 3  -> upper bound of range reached, last repetition
    i is printed -> prints 1 again

Third outer loop:
i = 2
total = di[2] = 33
--> first inner loop of third outer loop:
    j = i+1 = 3  -> upper bound of range is reached, only Repetition
    i is printed -> prints 2

Fourth (and final) outer loop:
i = 3 -> upper bound of range(len(di)) reached, last Repetition
total = di[3] = 87
since j = i+1 = 4, the inner loop does not get executed at all (both bounds of range are equal), so 3 doesn't get printed

end of code.