当你点开这篇博客,暂不敢说必喜好python,但至少证明对深浅拷贝有缘。或许你从事python时日已久,或许你同小编一道初入茅庐,或许你曾费很久去学深浅拷贝…但至今仍似懂非懂。那么,相信看完这篇博客定能让你“山重水复疑无路,柳暗花明又一村”😀!
一,内存相关的练习
practice one
v1 = {'k1':'v1','k2':[1,2,3]}
v2 = v1
result1 = v1 == v2
result2 = v1 is v2
print(result1)
print(result2)
注:“=”表示赋值,“==”表示值相等,“is”表示值和内存地址都相等
所以v1,v2值和内存地址都相等,即运行结果为True True
practice two
v1 = {'k1':'v1','k2':[1,2,3]}
v2 = v1
v1['k1'] = 'hepengli'
print(v2)
所以v1,v2值和内存地址还是相同,即运行结果为{‘k1’: ‘hepengli’, ‘k2’: [1, 2, 3]}
practice three
v1 = '人生苦短,我用Python'
v2 = [1,2,3,4,v1]
v1 = "人生苦短,用毛线Python"
print(v2)
即结果为[1, 2, 3, 4, ‘人生苦短,我用Python’]
practice four
info = [1,2,3]
userinfo = {'account':info, 'num':info, 'money':info}
info.append(9)
print(userinfo)
info = "丈八和尚"
print(userinfo)
即结果为
{‘account’: [1, 2, 3, 9], ‘num’: [1, 2, 3, 9], ‘money’: [1, 2, 3, 9]}
{‘account’: [1, 2, 3, 9], ‘num’: [1, 2, 3, 9], ‘money’: [1, 2, 3, 9]}
practice five
info = [1,2,3]
userinfo = [info,info,info,info]
info[0] = '感觉有点上头'
print(info,userinfo)
即结果为[‘感觉有点上头’, 2, 3] [[‘感觉有点上头’, 2, 3], [‘感觉有点上头’, 2, 3], [‘感觉有点上头’, 2, 3], [‘感觉有点上头’, 2, 3]]
practice six
info = [1,2,3]
userinfo = [info,info,info]
userinfo[2][0] = '脑阔疼'
print(info,userinfo)
即结果为[‘脑阔疼’, 2, 3] [[‘脑阔疼’, 2, 3], [‘脑阔疼’, 2, 3], [‘脑阔疼’, 2, 3]]
当不在为上面的几个小练习而犯迷糊时,深浅拷贝已无形间易如反掌!
二,深浅拷贝
one
假如一个变量为name=“hepengli”,那么常说拷贝一份就是复制粘贴,就算拷贝了一份🤣🤣🤣实则不然,在python中有个copy库
import copy
name = "hepengli"
name1 = copy.copy(name) # 浅拷贝
name2 = copy.deepcopy(name) # 深拷贝
小结:像字符串(str),整型(int),布尔型(bool)深浅拷贝没啥意思
two(list,set,dict)
①
import copy
list1 = ["hepengli", 1, 31]
list2 = copy.copy(list1) # 浅拷贝
print(list1 == list2) # True
print(list1 is list2) # False
print(list1[0] is list2[0]) # True
list3 = copy.deepcopy(list1) # 深拷贝
print(list1 == list2) # True
print(list1 is list2) # False
print(list1[0] is list2[0]) # True
小结:像list,set,dict只有一层,深浅拷贝也区别不大
②
import copy
list1 = [1, 2, [33, 99]]
list2 = copy.copy(list1) # 浅拷贝
list3 = copy.deepcopy(list1) # 深拷贝
print(list1 == list2) # True
print(list1 is list2) # False
print(list1[0] is list2[0]) # True
print(list1[2] == list2[2]) # True
print(list1[2] is list2[2]) # False
小结:像list,set,dict有多层嵌套,深浅拷贝就区别明显了(如上图)
总结:
浅拷贝:只拷贝第一层;
深拷贝:拷贝嵌套层次中的所有可变类型;
three(tuple)
①
import copy
tuple1 = (1, 2, 3, 4)
tuple2 = copy.copy(tuple1)
print(id(tuple1), id(tuple2))
tuple3 = copy.deepcopy(tuple1)
print(id(tuple1), id(tuple3))
1329399241440 1329399241440
1329399241440 1329399241440
这个和str类似
②
import copy
tuple1 = (1, 2, 3,[1, 2, 3], 4)
tuple2 = copy.copy(tuple1)
print(id(tuple1), id(tuple2))
tuple3 = copy.deepcopy(tuple1)
print(id(tuple1), id(tuple3))
2076671695264 2076671695264
2076671695264 2076671695184
当元组中嵌套有可变类型时,深拷贝就会改变