python中的深拷贝与浅拷贝

浅拷贝的时候,修改原来的对象,深拷贝的对象不会发生改变。


对象的赋值


对象的赋值实际上是对象之间的引用:当创建一个对象,然后将这个对象赋值给另外一个变量的时候,python并没有拷贝这个对象,而只是拷贝了这个对象的引用。

aList = ["kel","abc",123]
print(aList, id(aList))
bList = aListbList.append("add")print(aList, id(aList))
print(bList, id(bList))
(['kel', 'abc', 123], 139637569314688)
(['kel', 'abc', 123, 'add'], 139637569314688)
(['kel', 'abc', 123, 'add'], 139637569314688)

同样 numpy 下的数据结构与数据类型的转换(np.array vs. np.asarray)

np.array() 是深拷贝,np.asarray() 是浅拷贝

两者主要的区别在于,array(默认)复制一份对象,asarray不会执行这一动作。

def asarray(a, dtype=None, order=None):return array(a, dtype, copy=False, order=order)

示例一

import numpy as np  arr1=np.ones((3,3))  
arr2=np.array(arr1)  
arr3=np.asarray(arr1)  
print(arr2 is arr1) 
print(arr3 is arr1)
print('arr1:',arr1, id(arr1))  
print('arr2:',arr2, id(arr2)) 
print('arr3:',arr3, id(arr3))  
False
True
('arr1:', array([[ 1.,  1.,  1.],[ 1.,  1.,  1.],[ 1.,  1.,  1.]]), 139637569303856)
('arr2:', array([[ 1.,  1.,  1.],[ 1.,  1.,  1.],[ 1.,  1.,  1.]]), 139637569303776)
('arr3:', array([[ 1.,  1.,  1.],[ 1.,  1.,  1.],[ 1.,  1.,  1.]]), 139637569303856)

示例二

import numpy as np  arr1=np.ones((3,3))  
arr2=np.array(arr1)  
arr3=np.asarray(arr1)  
arr1[1]=2  
print('arr1:',arr1, id(arr1))  
print('arr2:',arr2, id(arr2)) 
print('arr3:',arr3, id(arr3))  
('arr1:', array([[ 1.,  1.,  1.],[ 2.,  2.,  2.],[ 1.,  1.,  1.]]), 139637569303296)
('arr2:', array([[ 1.,  1.,  1.],[ 1.,  1.,  1.],[ 1.,  1.,  1.]]), 139637569303376)
('arr3:', array([[ 1.,  1.,  1.],[ 2.,  2.,  2.],[ 1.,  1.,  1.]]), 139637569303296)

对象的复制


当你想修改一个对象,而且让原始的对象不受影响的时候,那么就需要使用到对象的复制,对象的复制可以通过三种方法实现:

a、 使用切片操作进行拷贝--slice operation
b、 使用工厂函数进行拷贝,list/dir/set--factoryfunction
c、 copy.copy()--use copymodule

在复制的时候,使用的是浅拷贝,复制了对象,但是对象中的元素,依然使用引用。

person = ["name",["savings",100.00]]
hubby = person[:] #切片操作
wifey = list(person) #使用工厂函数[id(x) for x in person,hubby,wifey]
print("The person is:", person, id(person))
print("The hubby is:", hubby, id(hubby))
print("The wifey is:", wifey, id(wifey))
('The person is:', ['name', ['savings', 100.0]], 139637569566984)
('The hubby is:', ['name', ['savings', 100.0]], 139637569544848)
('The wifey is:', ['name', ['savings', 100.0]], 139637569405656)
print("The person inside is:", [id(x) for x in person])
print("The hubby inside is:", [id(x) for x in hubby])
print("The wifey inside is:", [id(x) for x in wifey])
('The person inside is:', [139639860076144, 139637569544344])
('The hubby inside is:', [139639860076144, 139637569544344])
('The wifey inside is:', [139639860076144, 139637569544344])

hubby[0] = "kel"
wifey[0] = "jane"
hubby[1][1] = 50.0
print("The person is:", person, id(person))
print("The hubby is:", hubby, id(hubby))
print("The wifey is:", wifey, id(wifey))
('The person is:', ['name', ['savings', 50.0]], 139637570044992)
('The hubby is:', ['kel', ['savings', 50.0]], 139637569460344)
('The wifey is:', ['jane', ['savings', 50.0]], 139637569406160)
print("The person inside is:", [id(x) for x in person])
print("The hubby inside is:", [id(x) for x in hubby])
print("The wifey inside is:", [id(x) for x in wifey])
('The person inside is:', [139639860076144, 139637569810016])
('The hubby inside is:', [139637569356104, 139637569810016])
('The wifey inside is:', [139637569378272, 139637569810016])

在使用浅拷贝的时候,发现引用的id都是相同的,但是字符串的id却发生了变化,是因为在python中,字符串是不可变的,从而在每次进行修改的时候,都是新建一个对象,从而引用发生了变化。


copy模块


浅拷贝和深拷贝的操作都可以在copy模块中找到,其实copy模块中只有两个函数可用,copy()进行浅拷贝操作,而deepcopy()进行深拷贝操作


#1
import copy
aList = [1,"kel",[1,2,3]]
print("The aList is:", aList, id(aList))shadeList = copy.copy(aList)
print("The shadeList is:", shadeList, id(shadeList))deepList = copy.deepcopy(aList)
print("The deepList is:", deepList, id(deepList))aList[2].append("kel")print("The aList is:", aList, id(aList))print("The shadeList is:", shadeList, id(shadeList))print("The deepList is:", deepList, id(deepList))
('The aList is:', [1, 'kel', [1, 2, 3]], 139639722291712)
('The shadeList is:', [1, 'kel', [1, 2, 3]], 139639722170344)
('The deepList is:', [1, 'kel', [1, 2, 3]], 139637569586096)
('The aList is:', [1, 'kel', [1, 2, 3, 'kel']], 139639722291712)
('The shadeList is:', [1, 'kel', [1, 2, 3, 'kel']], 139639722170344)
('The deepList is:', [1, 'kel', [1, 2, 3]], 139637569586096)

#2
import copy
aList = [1,"kel",[1,2,3]]
print("The aList is:", aList, id(aList))shadeList = copy.copy(aList)
print("The shadeList is:", shadeList, id(shadeList))deepList = copy.deepcopy(aList)
print("The deepList is:", deepList, id(deepList))shadeList[2].append("kel")print("The aList is:", aList, id(aList))print("The shadeList is:", shadeList, id(shadeList))print("The deepList is:", deepList, id(deepList))
('The aList is:', [1, 'kel', [1, 2, 3]], 139637569846448)
('The shadeList is:', [1, 'kel', [1, 2, 3]], 139637569406520)
('The deepList is:', [1, 'kel', [1, 2, 3]], 139637569407240)
('The aList is:', [1, 'kel', [1, 2, 3, 'kel']], 139637569846448)
('The shadeList is:', [1, 'kel', [1, 2, 3, 'kel']], 139637569406520)
('The deepList is:', [1, 'kel', [1, 2, 3]], 139637569407240)

#3
import copy
aList = [1,"kel",[1,2,3]]
print("The aList is:", aList, id(aList))shadeList = copy.copy(aList)
print("The shadeList is:", shadeList, id(shadeList))deepList = copy.deepcopy(aList)
print("The deepList is:", deepList, id(deepList))deepList[2].append("kel")
print("The deepList is:", deepList, id(deepList))print("The aList is:", aList, id(aList))print("The shadeList is:", shadeList, id(shadeList))
('The aList is:', [1, 'kel', [1, 2, 3]], 139637569460776)
('The shadeList is:', [1, 'kel', [1, 2, 3]], 139637569461496)
('The deepList is:', [1, 'kel', [1, 2, 3]], 139637569585592)
('The deepList is:', [1, 'kel', [1, 2, 3, 'kel']], 139637569585592)
('The aList is:', [1, 'kel', [1, 2, 3]], 139637569460776)
('The shadeList is:', [1, 'kel', [1, 2, 3]], 139637569461496)

参考文献


numpy 下的数据结构与数据类型的转换(np.array vs. np.asarray)

numpy中array和asarray的区别

python中的深拷贝与浅拷贝

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/246749.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

从机器学习谈起

很好的一篇文章,转载自博客园:http://www.cnblogs.com/subconscious/p/4107357.html 在本篇文章中,我将对机器学习做个概要的介绍。本文的目的是能让即便完全不了解机器学习的人也能了解机器学习,并且上手相关的实践。这篇文档也算…

核函数

由于下一篇要学机器学习的另外一种模型——核模型,里面涉及到核函数,所以先找了一下核函数的相关知识。 在知乎上看到了一些比较好的解答,详细参考:http://www.zhihu.com/question/24627666 首先举一个核函数把低维空间映射到高…

关于Matlab编程的思考(待续)

Matlab编程的规范化思考 1.并行化 2.释放内存 3.需要调参的变量太多,可考虑将变量都放到一个结构体里面。 4.find(y),就是要找到y中那些非零项的指引 5.代码运行出现问题的时候,在命令行输入why就可以得到答案 6.输入bench可以给电脑跑分。 7.hom…

拉普拉斯锐化图像

在图像增强中,平滑是为了消除图像中噪声的干扰,或者降低对比度,与之相反,有时为了强调图像的边缘和细节,需要对图像进行锐化,提高对比度。 图的边缘是指在局部不连续的特征。 简要介绍一下原理&#xff1…

运动捕捉数据的描述ASF/AMC

运动捕捉数据有多种格式:ASF/AMC,BVH,C3D等,这三个是比较常用的,一般的matlab实验用的是ASF/AMC,其次就是BVH。 ASF/AMC文件格式是Acclaim Games公司设计开发的,全称是Acclaim Skeleton File/A…

应用深度学习(台大陈蕴侬李宏毅) Part1

History of Deep Learning Big Data & GPU 端到端 Universality Theorem Core Factors for Applied Deep Learning 参考文献 http://v.qq.com/vplus/578e2d6f5e1fadc1/foldervideos/8n1000201qzzkx5 Deep Learning ◦Goodfellow, Bengio, and Courville, “Deep Learning…

世界坐标

世界坐标是最直观反映人体在世界坐标系下运动位置的变化信息,对分析运动行为有重要的作用。下面介绍如何根据ASF/AMC文件计算人体各个关节的世界坐标。 根据前面讲的ASF/AMC文件的格式,可以知道人体运动可以看做是通过根节点root的平移以及其他关节绕其父…

12bit灰度图像映射到8bit显示及python 实现

图像显示和打印面临的一个问题是:图像的亮度和对比度能否充分突出关键部分。这里所指的“关键部分”在 CT 里的例子有软组织、骨头、脑组织、肺、腹部等等。 技术问题 1、显示器往往只有 8-bit, 而数据有 12- 至 16-bits。 2、如果将数据的 min 和 max…

人工神经网络——径向基函数(RBF)神经网络

此博客排版不好,重新用Markdown写了一篇,同时附上了代码,戳这里 本文摘自:《模式识别与智能计算——matlab技术实现第三版》与《matlab神经网络43个案例分析》 【注】蓝色字体为自己的理解部分 径向基函数神经网络的优点&#xf…

基于RBF简单的matlab手写识别

GetFeature.m %将图像分为25块,计算每一块的空白部分所占比例 function dataGetFeature(I) [row,col]find(I0); %返回数字的上下左右的边界 II(min(row):max(row),min(col):max(col)); %截取手写数字图像,使其紧包含数字边界&…

李宏毅机器学习课程-Transfer Learning

深度学习 -> 强化学习 ->迁移学习(杨强教授报告) 李宏毅机器学习课程-Transfer Learning 迁移学习-吴恩达 freeze 待处理的 理解深层神经网络中的迁移学习及TensorFlow实现 Transfer Learning模式 Similar domain, different task…

matlab实现RBF的相关函数

摘自《matlab神经网络43个案例分析》 (1)newrb() 该函数可以用来设计一个近似径向基网络(approximate RBF)。调用格式为: [net,tr]newrb(P,T,GOAL,SPREAD,MN,DF) 其中P为Q组输入向量组成的R*Q位矩阵,T为Q组目标分类向量组成的S*Q维矩阵。GOAL为均方误…

李宏毅机器学习课程-Structured Learning

Simple structured learning framework for python pystruct-github Slides for explaining structured prediction and PyStruct -github 一、Structured Learning-Unifed Framework 之前的input and output 都是vectors Training阶段就是找一个F来评估&#xff…

MATLAB GPU编程基础

原文地址:http://blog.sina.com.cn/s/blog_863f5cf90102uyrh.html 从Matlab2013版本开始,matlab将可以直接调用gpu进行并行计算,而不再需要安装GPUmat库。这一改动的好处是原有的matlab内置函数都可以直接运用,只要数据格式是gpuA…

matlab之norm函数

简单点说就是用来计算范数的一个函数。 假设A是一个矩阵,那么norm(A)或者norm(A,2)计算的就是A的2范数;同理norm(A,1)计算的就是1范数了. 2范数:计算步骤是先计算A*A‘(这里A’代表转置,也就是原矩阵*(原…

word_cloud

word_cloud word_cloud wordcloud_server

matlab之reshape函数

简单来说,reshape(A,m,n)就是用来把原矩阵的元素,按照列读取排成一行,然后按照指定的m*n矩阵再按列放好。比如原矩阵为 A 1 2 3 4 5 6 7 8 9 10 11 12 我们先给他按列拍成一排(变相说…

matlab之unwrap函数

网上的说法: 要计算一个系统相频特性,就要用到反正切函数,计算机中反正切函数规定,在一、二象限中的角度为0~pi,三四象限的角度为0~-pi。 若一个角度从0变到2pi,但实际得到的结果是…

画图网页http://weavesilk.com/

画图网页 http://weavesilk.com/

matlab之bsxfun函数

<span style"font-size:18px;color:#ff0000;">简单的调用方法&#xff1a;</span> bsxfun(plus&#xff0c;A&#xff0c;B)&#xff0c;其中plus代表的是加法&#xff0c;还可以换成减法minus&#xff0c;乘法times等&#xff0c;可以参考matlab里面的帮…