深浅拷贝
浅拷贝:只考贝第一层
1 a = [[1,2],3,4] 2 b = a.copy() 3 b[1]=99 4 print(a,b) 5 b[0][1]=88 6 print(a,b) 7 8 [[1, 2], 3, 4] [[1, 2], 99, 4] 9 [[1, 88], 3, 4] [[1, 88], 99, 4]
1 husband = ["xiaohu",123,[15000,9000]] 2 3 wife = husband.copy() 4 wife[0] = "xiaopang" 5 wife[1] = 345 6 husband[2][1] -= 3000 7 print(wife)
深拷贝:拷贝所有(克隆一份)
import copy
a = [[1,2],3,4] b = copy.deepcopy(a) b[1]=99 print(a,b) b[0][1]=88 print(a,b) [[1, 2], 3, 4] [[1, 2], 99, 4] [[1, 2], 3, 4] [[1, 88], 99, 4]
1 import copy 2 3 husband = ["xiaohu",123,[15000,9000]] 4 5 xiaosan = copy.deepcopy(husband) 6 xiaosan[0] = "xiaosan" 7 xiaosan[1] = "666" 8 xiaosan[2][1] -= 1000 9 print(xiaosan)
import copy husband = ["xiaohu",123,[15000,9000]] wife = husband.copy() wife[0] = "xiaopang" wife[1] = 345 husband[2][1] -= 3000 #浅拷贝 print(wife) xiaosan = copy.deepcopy(husband) xiaosan[0] = "xiaosan" xiaosan[1] = "666" xiaosan[2][1] -= 1000 #深拷贝 print(xiaosan)