3 回答

TA貢獻1836條經驗 獲得超3個贊
a = b在 Python 中的作用存在誤解。
這并不意味著“修改a數據,使其與b數據相同”。
相反,它的意思是:“從現在開始,使用變量名a來引用由變量引用的相同數據b”。
請參閱此示例:
data = ['a', 'b', 'c']
x = data[0] # x is now 'a', effectively the same as: x = 'a'
x = 'b' # x is now 'b', but `data` was never changed
data[0] = 'm' # data is now ['m', 'b', 'c'], x is not changed
data[1] = 'm' # data is now ['m', 'm', 'c'], x is not changed
原始代碼也會發生同樣的情況:
for i in arr[0]:
# i is now referencing an object in arr[0]
i = 1
# i is no longer referencing any object in arr, arr did not change

TA貢獻1909條經驗 獲得超7個贊
在 python 中,變量不是指針。
循環內部發生的事情是
1)for each element in the array
2)copy value of the array element to iterator(Only the value of the array element is copied and not the reference to its memory)
3)perform the logic for each iteration.
如果您對迭代器對象進行任何更改,您只會修改變量值的副本,而不是原始變量(數組元素)。
添加回答
舉報