更改2D数组元素的值将更改整个列

时间:2020-06-19 23:54:55

标签: python performance numpy while-loop optics-algorithm

当我打印我的arr值时,我得到的2D数组的值正确,但是当我退出while循环时,我的值都是错误的。

我不确定自己在做什么错。

    #num runs
    n = 4

    x = np.linspace(-1,1,n)
    y = np.linspace(-1,1,n)
    x1,y1 = np.meshgrid(x, y)

    l = np.linspace(0,1000,n)
    x = np.linspace(-1,1,n)
    p1,p2 = np.meshgrid(l,l)

    w020 = 5*(y1**2+x1**2)

    row, cols = (n,n)
    arr = [[0]*cols]*row
  
    i = 0
    p = 0
    while i < n:
        i += 1
        p=0
        while p < n:
            arr[i-1][p] = 2+2*math.cos(2*math.pi*w020[i-1,p])
            p += 1
    print(arr)       

1 个答案:

答案 0 :(得分:0)

创建2D数组的方式会创建一个浅表

    arr = [[0]*cols]*row

相反,如果要更新列表的元素,则应使用

   rows, cols = (5, 5) 
   arr = [[0 for i in range(cols)] for j in range(rows)] 

说明

一个人可以使用:

   arr = [0]*N 

   arr = [0 for i in range(N)] 

在第一种情况下,数组的所有索引都指向同一整数对象

enter image description here

,当您将值分配给特定索引时,会创建一个新的int对象,例如arr[4] = 5创建

enter image description here

现在让我们看看在创建列表列表时会发生什么,在这种情况下,我们顶部列表的所有元素都将指向同一列表

enter image description here

如果更新任何索引的值,将创建一个新的int对象。但是,由于所有顶级列表索引都指向同一列表,因此所有行将看起来相同。并且您会感觉到更新元素正在更新该列中的所有元素。

enter image description here

信用:感谢Pranav Devarakonda的简单解释here