Python自学之乐-浅析Python的深浅拷贝

import copy
#浅拷贝
person = ["name",["saving",1000]]
p1 = copy.copy(person)
p2 = person.copy() #两种都是浅拷贝
print(person,p1,p2)
###结果为 ['name', ['saving', 1000]] ['name', ['saving', 1000]] ['name', ['saving', 1000]]
person[0] = "clark"
print(person,p1,p2)
###结果为['clark', ['saving', 1000]] ['name', ['saving', 1000]] ['name', ['saving', 1000]] 单个字符未改变
person[1][1] = 2000
print(person,p1,p2)#记住这两种方式的最后结果
####结果为['clark', ['saving', 2000]] ['name', ['saving', 2000]] ['name', ['saving', 2000]] 列表值改变,对应浅拷贝里的列表值也相应改变

p1[0] = "徐宏彪"
print(person,p1,p2)
##结果为['clark', ['saving', 2000]] ['徐宏彪', ['saving', 2000]] ['name', ['saving', 2000]]
p1[1][1] = 3000
print(person,p1,p2)
##结果为['clark', ['saving', 3000]] ['徐宏彪', ['saving', 3000]] ['name', ['saving', 3000]]   结论同上

#深拷贝
info  = ["name",["love",20]]
info1 = copy.deepcopy(info)
info2 = copy.deepcopy(info)
print(info,info1,info2)
info[0] = "clark"
print(info,info1,info2)
info[1][1] = 30
print(info,info1,info2)
info1[1][1] = 40
print(info,info1,info2)#深拷贝,各自为独立 所以不管怎么修改任意一个,其他的June不变






posted on 2017-07-26 00:18  clarkxhb  阅读(103)  评论(0编辑  收藏  举报