CHH3213 / Note-Ubuntu_CHH3213

ubuntu系统CHH3213上做的笔记
0 stars 0 forks source link

31. python 使用循环遍历array数组元素赋值出现的问题 #31

Open CHH3213 opened 3 years ago

CHH3213 commented 3 years ago

例子1--遇到array数组赋值给自身时会出错

A = np.array([[1,2,3],[1,1,1]])
for i in range(2):
    A[i] = np.array(A[i])/np.linalg.norm(A[i])
    print(A[i])

此时打印出的数据为:

[0 0 0]
[0 0 0]

例子2--列表赋值给自身不会出错

A = [[1,2,3],[1,1,1]]
for i in range(2):
    A[i] = np.array(A[i])/np.linalg.norm(A[i])
    print(A[i])

此时打印出的数据为:

[0.26726124 0.53452248 0.80178373]
[0.57735027 0.57735027 0.57735027]

例子3--引入中间变量再赋值,就不会出错

A = np.array([[1,2,3],[1,1,1]])
a = []
for i in range(2):
    temp = np.array(A[i])/np.linalg.norm(A[i])
    a.append(temp)
    print(a[i])

此时打印出的数据为:

[0.26726124 0.53452248 0.80178373]
[0.57735027 0.57735027 0.57735027]