为什么我会得到如此奇怪的循环行为值?
Why I am getting such strange behavior value for loop?
a = []
for i in range(10):
a.append (i*i)
for a[i] in a:
print(a[i])
对于上述代码,我得到的输出如下:
0
1
4
9
16
25
36
49
64
64
我不明白为什么 64 会重复两次。如果有人知道正确的原因,请详细解释我。
所以基本上当第一个循环结束时,i 的值为 9(因为它在 10 范围内)
因此,当您开始第二个循环时,每次迭代都会更改 a[i]
的值,即早于 9 的最后一个元素。
所以,
a = []
for i in range(10):
a.append (i*i)
# Here: i = 10 and a = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(a[i])
# While iterating through this, the value of a[i] changes every item and is equal
# the current element of a
# When it reaches the last element, it's already a[9] so the previous value is
# printed.
因此在每次迭代中:
currentElement a[i] a
0 0 [0, 1, 4, 9, 16, 25, 36, 49, 64, 0]
1 1 [0, 1, 4, 9, 16, 25, 36, 49, 64, 1]
4 4 [0, 1, 4, 9, 16, 25, 36, 49, 64, 4]
9 9 [0, 1, 4, 9, 16, 25, 36, 49, 64, 9]
16 16 [0, 1, 4, 9, 16, 25, 36, 49, 64, 16]
25 25 [0, 1, 4, 9, 16, 25, 36, 49, 64, 25]
36 36 [0, 1, 4, 9, 16, 25, 36, 49, 64, 36]
49 49 [0, 1, 4, 9, 16, 25, 36, 49, 64, 49]
64 64 [0, 1, 4, 9, 16, 25, 36, 49, 64, 64]
64 64 [0, 1, 4, 9, 16, 25, 36, 49, 64, 64]
造成这种行为
建议循环应该像 for item in a:
,让我们尝试了解 for a[i] in a:
的行为
a = []
for i in range(10):
a.append (i*i)
print("Values before loop")
print(a, i)
for a[i] in a:
print(a[i])
print("Values after loop")
print(a, i)
Values before loop
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 9
0
1
4
9
16
25
36
49
64
64
Values after loop
[0, 1, 4, 9, 16, 25, 36, 49, 64, 64] 9
当您在上面的循环中迭代时,i 始终为 9,因此迭代 for a[i] in a
将后续值从 a 分配给 a[i],即 a[9],因此,在第二次最终迭代中,值 a[9] 变为 a[8],即 64
a = []
for i in range(10):
a.append (i*i)
for a[i] in a:
print(a[i])
对于上述代码,我得到的输出如下:
0
1
4
9
16
25
36
49
64
64
我不明白为什么 64 会重复两次。如果有人知道正确的原因,请详细解释我。
所以基本上当第一个循环结束时,i 的值为 9(因为它在 10 范围内)
因此,当您开始第二个循环时,每次迭代都会更改 a[i]
的值,即早于 9 的最后一个元素。
所以,
a = []
for i in range(10):
a.append (i*i)
# Here: i = 10 and a = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(a[i])
# While iterating through this, the value of a[i] changes every item and is equal
# the current element of a
# When it reaches the last element, it's already a[9] so the previous value is
# printed.
因此在每次迭代中:
currentElement a[i] a
0 0 [0, 1, 4, 9, 16, 25, 36, 49, 64, 0]
1 1 [0, 1, 4, 9, 16, 25, 36, 49, 64, 1]
4 4 [0, 1, 4, 9, 16, 25, 36, 49, 64, 4]
9 9 [0, 1, 4, 9, 16, 25, 36, 49, 64, 9]
16 16 [0, 1, 4, 9, 16, 25, 36, 49, 64, 16]
25 25 [0, 1, 4, 9, 16, 25, 36, 49, 64, 25]
36 36 [0, 1, 4, 9, 16, 25, 36, 49, 64, 36]
49 49 [0, 1, 4, 9, 16, 25, 36, 49, 64, 49]
64 64 [0, 1, 4, 9, 16, 25, 36, 49, 64, 64]
64 64 [0, 1, 4, 9, 16, 25, 36, 49, 64, 64]
造成这种行为
建议循环应该像 for item in a:
,让我们尝试了解 for a[i] in a:
a = []
for i in range(10):
a.append (i*i)
print("Values before loop")
print(a, i)
for a[i] in a:
print(a[i])
print("Values after loop")
print(a, i)
Values before loop
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 9
0
1
4
9
16
25
36
49
64
64
Values after loop
[0, 1, 4, 9, 16, 25, 36, 49, 64, 64] 9
当您在上面的循环中迭代时,i 始终为 9,因此迭代 for a[i] in a
将后续值从 a 分配给 a[i],即 a[9],因此,在第二次最终迭代中,值 a[9] 变为 a[8],即 64