我不明白下面代码的第二个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循环中如何受到第一个循环的影响?有继承吗?请原谅这里的新手。
len(di)
是4.所以循环
for i in range(len(di)):
将重复4次。由于range
的工作方式(从下限开始,默认为0,如果没有指定,则低于上限1),i
将在第一次重复时为0
,在第二次重复时为1
,依此类推。要计算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
equals 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.
在编程语言中,变量可用于范围内。当您使用新变量开始循环时,它将可供使用,直到您结束它。
当你开始学习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”语句完成。