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.
如果您对迭代器对象进行任何更改,您只会修改变量值的副本,而不是原始变量(数组元素)。
添加回答
举报