首页 > 编程语言 > 详细

python基础之深浅拷贝

时间:2019-11-18 21:26:41      阅读:67      评论:0      收藏:0      [点我收藏+]
深浅拷贝:
对于字符串(str),数字(int),布尔类型(bool)等类型深浅拷贝都是开辟新内存
对于列表(list),集合(set),字典(dict)深浅拷贝可变类型都一样,如[1,2,3]
对于列表(list),集合(set),字典(dict)存在嵌套的深浅拷贝不一样,如[1,2,3,[4,5,6]],浅拷贝只拷贝[1,2,3],深拷贝[1,2,3,[4,5,6]]
浅拷贝:拷贝第一层
深拷贝:拷贝所有数据(可变)
应该每次都拷贝一份(但由于小数据池,未拷贝)
v = ‘sundy‘
import copy
v1 = copy.copy(v)
v2 =copy.deepcopy(v)
print(id(v),id(v1))
print(id(v),id(v2))
D:\python3.6\python3.6.exe D:/python_code/day01/day06.py
1761132524464 1761132524464
1761132524464 1761132524464

v = [1,2,3,4]
import copy
v1 = copy.copy(v)
v2 =copy.deepcopy(v)
print(id(v),id(v1))
print(id(v),id(v2))
D:\python3.6\python3.6.exe D:/python_code/day01/day06.py
2561119066504 2561120559432
2561119066504 256112055962
浅拷贝:
v = [1,2,3,4,[5,6,7]]
import copy
v1 = copy.copy(v)
print(v == v1)
print(v is v1)
print(v[4] == v1[4])
print(v[4] is v1[4])
D:\python3.6\python3.6.exe D:/python_code/day01/day06.py
True
False
True
True
 
 
v = [1,2,3,4,[5,6,7]]
import copy
v1 = copy.copy(v) #浅拷贝只拷贝空壳[]
print(id(v),id(v1))
print(id(v[2]),id(v1[2]))
print(id(v[4]),id(v1[4]))
 
D:\python3.6\python3.6.exe D:/python_code/day01/day06.py
1978756340040 1978757833096
1689026736 1689026736
1978756340104 1978756340104
 
#深拷贝
v = [1,2,3,4,[5,6,7]]
import copy
v1 = copy.deepcopy(v)
print(v == v1)
print(v is v1)
print(v[4] == v1[4])
print(v[4] is v1[4])

D:\python3.6\python3.6.exe D:/python_code/day01/day06.py
True
False
True
False
 
 
v2 =copy.deepcopy(v)#深拷贝拷贝嵌套里面空壳[](即可变类型)
print(id(v),id(v2))
print(id(v[2]),id(v2[2]))
print(id(v[4]),id(v2[4]))
print(id(v[4][1]),id(v2[4][1]))

D:\python3.6\python3.6.exe D:/python_code/day01/day06.py
2764609460552 2764610953608
1692303536 1692303536
2764609460616 2764609460616
2764609460552 2764610953800
1692303536 1692303536
2764609460616 2764610955080
1692303632 1692303632
特殊情况
对于不可变类型的元组深浅拷贝内存地址不变
v = (1,2,3,4,5)
import copy
v1 = copy.copy(v)
print(id(v),id(v1))
v1 = copy.deepcopy(v)
print(id(v),id(v1))
D:\python3.6\python3.6.exe D:/python_code/day01/day06.py
1747241185792 1747241185792
1747241185792 1747241185792
对于不可变类型的元组存在可变类型深拷贝内存地址不一样
v = (1,2,3,4,5,[6,7,8,9])
import copy
v1 = copy.copy(v)
print(id(v),id(v1))
v1 = copy.deepcopy(v)
print(id(v),id(v1))
D:\python3.6\python3.6.exe D:/python_code/day01/day06.py
2430290597736 2430290597736
2430290597736 2430291562760

总结
不可变类型:数字(int),字符串(str),布尔(bool),元组(tuple)
可变类型:列表(list),字典(dict),集合(set)
深浅拷贝只拷贝可变类型的内存地址

python基础之深浅拷贝

原文:https://www.cnblogs.com/sundy08/p/11884926.html

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