import numpy as np
import copy
a=np.mat("1 2 3;4 5 6;7 8 9")
print(a)
b=a
b[0,0]=0
print(a)
print(b)
print("-"*10)
输出结果
[[1 2 3]
[4 5 6]
[7 8 9]]
[[0 2 3]
[4 5 6]
[7 8 9]]
[[0 2 3]
[4 5 6]
[7 8 9]]
----------
可以看到 直接赋值时改变 b 同时 改变 a 。
python 除了字符串,元组,数字等是值传递,其他则为引用传递。
import numpy as np
import copy
a=np.mat("1 2 3;4 5 6;7 8 9")
print(a)
b=a.copy()
b[0,0]=0
print(a)
print(b)
print("-"*10)
输出结果
[[1 2 3]
[4 5 6]
[7 8 9]]
[[1 2 3]
[4 5 6]
[7 8 9]]
[[0 2 3]
[4 5 6]
[7 8 9]]
numpy 的 copy 函数为深拷贝 浅拷贝为 b=a.view() 函数
import numpy as np
import copy
a=[[1,2,3],[4,5,6]]
print(a)
b=a.copy()
b[0][0]=0
print(a)
print(b)
print("-"*10)
输出结果
[[1, 2, 3], [4, 5, 6]]
[[0, 2, 3], [4, 5, 6]]
[[0, 2, 3], [4, 5, 6]]
----------
使用浅拷贝 只 拷贝最外层的列表结构,对内部依然是赋值
import numpy as np
import copy
a=[[1,2,3],[4,5,6]]
print(a)
b=a.copy()
b[0]=[0,2,3]
print(a)
print(b)
print("-"*10)
输出结果
[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]
[[0, 2, 3], [4, 5, 6]]
----------
import numpy as np
import copy
a=[[1,2,3],[4,5,6]]
print(a)
b=a.copy()
b[0]=[0,2,3]
b[0][0]=3
print(a)
print(b)
print("-"*10)
输出结果
[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]
[[3, 2, 3], [4, 5, 6]]
----------
标签:python,np,print,import,拷贝,copy,numpy
From: https://www.cnblogs.com/XUEYEYU/p/17447009.html