首页 > 其他 > 详细

赋值、浅拷贝以及深拷贝的区别

时间:2018-01-21 00:47:10      阅读:240      评论:0      收藏:0      [点我收藏+]

 

字符串赋值

>>>
>>> str1 = ‘standby‘
>>> 
>>> str2 = str1
>>> 
>>> print str1==str2, str1 is str2
True True
>>> 
>>> id(str1)
139792206350496
>>> id(str2)
139792206350496
>>> 

补充

>>> 
>>> a = ‘standby‘
>>> b = ‘standby‘
>>> 
>>> a == b
True
>>> a is b
True
>>> 
>>> id(a)
139792206350496
>>> id(b)
139792206350496
>>> 

 

字符串浅拷贝方式一

>>> 
>>> import copy
>>> str1 = ‘standby‘
>>> 
>>> str2 = copy.copy(str1)
>>> 
>>> print str1==str2, str1 is str2
True True
>>> 
>>> id(str1)
139792206350496
>>> id(str2)
139792206350496
>>> 

字符串浅拷贝方式二

>>> 
>>> str1 = ‘standby‘
>>> 
>>> str2 = str1[:]
>>> 
>>> print str1==str2, str1 is str2
True True
>>> 
>>> id(str1)
139792206350496
>>> id(str2)
139792206350496
>>> 

 

字符串深拷贝

>>> 
>>> import copy
>>> str1 = ‘standby‘
>>> 
>>> str2 = copy.deepcopy(str1)
>>> 
>>> print str1==str2, str1 is str2
True True
>>> 
>>> id(str1)
139792206350496
>>> id(str2)
139792206350496
>>> 

 

 

列表赋值

>>> 
>>> list1 = [1, 2, [1, 2]]
>>> 
>>> list2 = list1
>>> 
>>> print list1==list2, list1 is list2
True True
>>> 
>>> id(list1)
139792206344992
>>> id(list2)
139792206344992
>>> 

补充

>>> 
>>> list1 = [1, 2, [‘a‘, ‘c‘]]
>>> list2 = [1, 2, [‘a‘, ‘c‘]]
>>> 
>>> list1 == list2
True
>>> list1 is list2
False
>>> 
>>> id(list1)
139792206356704
>>> id(list2)
139792206348088
>>> 

 

列表浅拷贝方式一

>>> 
>>> import copy
>>> list1 = [1, 2, [1, 2]]
>>> 
>>> list2 = copy.copy(list1)
>>> 
>>> print list1==list2, list1 is list2
True False
>>> 
>>> 
>>> id(list1)
139792206344920
>>> id(list2)
139792206356560
>>> 

列表浅拷贝方式二

>>> 
>>> list1 = [1, 2, [1, 2]]
>>> 
>>> list2 = list1[:]
>>> 
>>> print list1==list2, list1 is list2
True False
>>> 
>>> id(list1)
139792206356704
>>> id(list2)
139792206344992
>>> 

  

列表深拷贝

>>> 
>>> import copy
>>> list1 = [1, 2, 3, 4]
>>> 
>>> list2 = copy.deepcopy(list1)
>>> 
>>> print list1==list2, list1 is list2
True False
>>> 
>>> id(list1)
139792206344992
>>> id(list2)
139792206344920
>>> 

 

 

浅拷贝情况下的修改

>>> 
>>> import copy
>>> list1 = [1, 2, [‘a‘, ‘c‘]]
>>> 
>>> list2 = copy.copy(list1)
>>> print list1==list2, list1 is list2
True False
>>> id(list1)
139792206358720
>>> id(list2)
139792206359080
>>> 
>>> list2[2].append(‘k‘)
>>> print list2,list1
[1, 2, [‘a‘, ‘c‘, ‘k‘]] [1, 2, [‘a‘, ‘c‘, ‘k‘]]
>>> id(list1)
139792206358720
>>> id(list2)
139792206359080
>>> 

  

深拷贝情况下的修改

>>> 
>>> import copy
>>> list1 = [1, 2, [‘a‘, ‘c‘]]
>>> 
>>> list2 = copy.deepcopy(list1)
>>> print list1==list2, list1 is list2
True False
>>> id(list1)
139792206344920
>>> id(list2)
139792206358720
>>> 
>>> list2[2].append(‘k‘)
>>> print list2,list1
[1, 2, [‘a‘, ‘c‘, ‘k‘]] [1, 2, [‘a‘, ‘c‘]]
>>> id(list1)
139792206344920
>>> id(list2)
139792206358720
>>> 

  

 

 

赋值、浅拷贝以及深拷贝的区别

原文:https://www.cnblogs.com/standby/p/8322307.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!