При изменении значения элемента 2D-массива изменяется весь столбец - PullRequest
1 голос
/ 20 июня 2020

Когда я печатаю свое arr значение, я получаю правильные значения для своего 2D-массива, но когда я выхожу из while l oop, все мои значения неверны.

Я не уверен, что делаю неправильно.

    #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 голосов
/ 21 июня 2020

То, как вы создали 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

and when you assign a value to a particular index, a new int object is created, for eg arr[4] = 5 creates

enter image description here

Now let us see what happens when we create a list of list, in this case, all the elements of our top list will point to the same list

enter image description here

And if you update the value of any index a new int object will be created. But since all the top-level list indexes are pointing at the same list, all the rows will look the same. And you will get the feeling that updating an element is updating all the elements in that column.

enter image description here

Credits: Thanks to Пранав Девараконда для простого объяснения здесь

...