本文介紹numpy的矩陣賦值操作和copy操作
Demo.py
# =的賦值方式會帶有關(guān)聯(lián)性
import numpy as np
a = np.arange(4)
# array([0, 1, 2, 3])
b = a
c = a
d = b
#改變a的第一個值,b闺魏、c、d的第一個值也會同時改變。
a[0] = 11
print(a)
# array([11, 1, 2, 3])
#確認(rèn)b罚舱、c、d是否與a相同。
b is a # True
c is a # True
d is a # True
#同樣更改d的值,a赢底、b、c也會改變柏蘑。
d[1:3] = [22, 33] # array([11, 22, 33, 3])
print(a) # array([11, 22, 33, 3])
print(b) # array([11, 22, 33, 3])
print(c) # array([11, 22, 33, 3])
#copy()的賦值方式?jīng)]有關(guān)聯(lián)性
b = a.copy() # deep copy
print(b) # array([11, 22, 33, 3])
a[3] = 44
print(a) # array([11, 22, 33, 44])
print(b) # array([11, 22, 33, 3])
結(jié)果:
[11 1 2 3]
[11 22 33 3]
[11 22 33 3]
[11 22 33 3]
[11 22 33 3]
[11 22 33 44]
[11 22 33 3]