使用for循环在python中分配数组值

时间:2019-10-20 10:57:31

标签: python arrays python-3.x for-loop

在Python3中动态创建2D数组时,在以下情况下不会更新值:

no_col = 3
no_row = 4

arr = [[0 for x in range(no_col)] for y in range(no_row)] 

for i in arr[0]:
    i = 1

arr值

0 0 0
0 0 0
0 0 0
0 0 0

但是在使用范围时,值会更新

for i in range(no_col):
    arr[0][i] = 1

arr值

1 1 1
0 0 0
0 0 0
0 0 0

为什么会这样?

3 个答案:

答案 0 :(得分:2)

这是因为您为每个人

for i in arr[0]:
    i = 1

等效于

for idx in range(len(arr[0])):
    i = arr[0][idx]
    i = 1

您不能为每个循环修改数组,因为每次迭代都会创建一个新变量,并且您要修改新变量的值而不是数组

看看this

答案 1 :(得分:2)

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

答案 2 :(得分:0)

在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.

如果对迭代器对象进行任何更改,则仅在修改变量值的副本,而不是原始变量(数组元素)。