一、总结
一句话总结:
numpy的copy方法是浅拷贝,numpy实现深度拷贝,可以用copy库的deepcopy方法
2、浅拷贝
a = np.arange(4)
# b = a.copy()
b = np.copy(a)
print(a)
print(b)
print(id(a))
print(id(b))
[0 1 2 3]
[0 1 2 3]
1937862920512
1937867598384
3、深拷贝
实现深度拷贝,可以用copy库的deepcopy方法
import copy
a = np.array([1, 'm', [2, 3, 4]], dtype=object)
c = copy.deepcopy(a)
二、数组拷贝
博客对应课程的视频位置:13、数组拷贝-范仁义-读书编程笔记
https://www.fanrenyi.com/video/38/356
1、直接赋值方式
In [1]:
import numpy as np
a = np.arange(4)
b = a
print(a)
print(b)
[0 1 2 3]
[0 1 2 3]
In [2]:
a[0] = 199
b[1:3] = [7,8]
print(a)
print(b)
[199 7 8 3]
[199 7 8 3]
In [3]:
print(id(a))
print(id(b))
print(b is a)
1937866698464
1937866698464
True
2、浅拷贝
In [4]:
a = np.arange(4)
# b = a.copy()
b = np.copy(a)
print(a)
print(b)
print(id(a))
print(id(b))
[0 1 2 3]
[0 1 2 3]
1937862920512
1937867598384
In [5]:
a[0] = 199
b[1:3] = [7,8]
print(a)
print(b)
[199 1 2 3]
[0 7 8 3]
数组里面有对象的时候
In [6]:
a = np.array([1, 'm', [2, 3, 4]], dtype=object)
print(a)
[1 'm' list([2, 3, 4])]
In [7]:
b = np.copy(a)
print(a)
print(b)
[1 'm' list([2, 3, 4])]
[1 'm' list([2, 3, 4])]
In [8]:
b[2][0] = 10
print(a)
print(b)
[1 'm' list([10, 3, 4])]
[1 'm' list([10, 3, 4])]
In [9]:
print(id(a[2]))
print(id(b[2]))
1937867498696
1937867498696
3、深拷贝
实现深度拷贝,可以用copy库的deepcopy方法
In [10]:
import copy
a = np.array([1, 'm', [2, 3, 4]], dtype=object)
c = copy.deepcopy(a)
print(a)
print(c)
[1 'm' list([2, 3, 4])]
[1 'm' list([2, 3, 4])]
In [11]:
c[2][0] = 10
print(a)
print(c)
[1 'm' list([2, 3, 4])]
[1 'm' list([10, 3, 4])]
In [12]:
print(id(a[2]))
print(id(c[2]))
1937852899272
1937861691592
In [ ]:
我的旨在学过的东西不再忘记(主要使用艾宾浩斯遗忘曲线算法及其它智能学习复习算法)的偏公益性质的完全免费的编程视频学习网站;有各种前端、后端、算法、大数据、人工智能等课程。