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 會重復兩次。如果有人知道正確的原因,請詳細解釋我。
uj5u.com熱心網友回復:
建議回圈應該像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
uj5u.com熱心網友回復:
所以基本上當第一個回圈結束時,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]
導致這種行為
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/456882.html
標籤:Python python-3.x 循环 for循环
上一篇:為每一步繪制一個點i
