@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* 배열; 오류의 경우
>>> C=[]
>>> D=[3,4]
>>> C.append(D)
>>> C.append(D)
>>> C => [[3,4],[3,4]]
>>> C[1][1] -> 4 # OK
>>> C[1][0] = 5 # update C[[i][0] to a new value (=5)
>>> C => [[5,4],[5,4]] # Wrong; 5 appears at both places
How to filx it? ------------------
Why? >> D=[3,4] 리스트[3,4]가 변수D에 할당되면
D가 리스트를 포인팅한다.
D가 C에 2회 입력된다.
그러나 두 리스트는 동일한 메모리를 차지한다.
[3,4]의 어느 하나를 변경하면 나머지도 변경된다.
Fix >>
>>> C=[]
>>> for j in range(0,2):
... C.append([])
...
>>> C => [[],[]]
>>> for j in range(0,2):
... C[j].append(3)
... C[j].append(4)
...
>>> C => [[3,4],[3,4]]
>>> C[1][0]=5
>>> C => [[3,4],[5,4]] # OK!
[e.g.] 2차원 배열 만들기.
>>> A=[]
>>> for i in range(0,4):
... A.append(0)
...
>>> A => [0,0,0,0] ; 1차원 배열
>>> B=[]
>>> for i in range(0,4):
... B.append(A)
...
>>> B => [ [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0] ]
looks good. hwr, indexing it makes some problems.
>>> A[2]=2 => [0,0,2,0]
>>> B[0][1]=3
>>> B => [ [0,3,0,0], [0,3,0,0], [0,3,0,0], [0,3,0,0] ] ; Wrong!
순서; ⒈ A=[] # init
⒉ A=[0,0,0,0]
⒊ A=[ [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0] ] ; Wrong!
A different try;
순서; ⒈ C=[] # init
⒉ C=[ [], [], [], [] ]
⒊ C=[ [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0] ]
>>> C=[]
>>> for i in range(0,4):
... C.append([])
...
>>> C => [ [], [], [], [] ]
>>> for i in range(0,4):
... for j in range(0,4):
... C[i].append(0)
>>> C => C=[ [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0] ]
>>> C[1][2]=5
>>> C => C=[ [0,0,0,0], [0,0,5,0], [0,0,0,0], [0,0,0,0] ]
# OK!
Using numpy library;
>>> import numpy as np
>>> A = np.zeros((5)) # define A as a one-dimensional array of 5 elements
# initialized to zeros
>>> print(A)
-> [0. 0. 0. 0. 0.]
>>> C = np.zeros((4,4)) # define C as a two-dimensional array of 4 by 4
# initialized to zeros
>>> print(C)
-> [[0. 0. 0. 0.]
>>> C = np.zeros((4,4)) # define C as a two-dimensional array of 4 by 4
# initialized to zeros
>>> print(C)
-> [[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
>>> C[1][2] = 5
>>> print(C)
-> [[0. 0. 0. 0.]
[0. 0. 5. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
//