import copy from copy import deepcopy origin = [1,2,[3,4]] # origin里面有三个元素,1,2,[3,4] copy1 = copy.copy(origin) copy2 = deepcopy(origin) print(copy1 == copy2) # True print(copy1 is copy2) # False # copy1 和copy2看上去相同,但已经不是同一个object origin[2][0] = "hey!" print(origin) # [1, 2, ['hey!', 4]] print(copy1) # [1, 2, ['hey!', 4]] print(copy2) # [1, 2, [3, 4]]
可以看到 copy1,也就是 shallowcopy 跟着 origin 改变了。而 copy2 ,也就是 deepcopy 并没有变。可以看出deepcopy 更加符合我们对「复制」的直觉定义: 一旦复制出来了,就应该是独立的了。如果我们想要的是一个字面意义的「copy」,那就直接用deepcopy 即可。
2 .字典数据类型的copy
a = { "name":["An","Assan"] } b = a.copy() a["name"] = ["An"] print(a) print(b) del a['name'] print(a) print(b) """ {'name': ['An']} {'name': ['An', 'Assan']} {} {'name': ['An', 'Assan']} """
a = { "name":["An","Assan"] } b = a.copy() a["name"].append("Hunter") print(a) print(b) a['name'].remove('An') print(a) print(b) """ {'name': ['An', 'Assan', 'Hunter']} {'name': ['An', 'Assan', 'Hunter']} {'name': ['Assan', 'Hunter']} {'name': ['Assan', 'Hunter']} """
a = { "name":["An","Assan"] } b = deepcopy(a) a["name"].append("Hunter") print(a) print(b) """ {'name': ['An', 'Assan', 'Hunter']} {'name': ['An', 'Assan']} """
list2 = list1 list1.append(5) print(list1) # [1, 2, [3, 4], 5] print(list2) # [1, 2, [3, 4], 5] list1[2].remove(3) print(list1) # [1, 2, [4], 5] print(list2) # [1, 2, [4], 5]
list1 = [1,2,[3,4]] list2 = list1[:] list1.append(5) print(list1) # [1, 2, [3, 4], 5] print(list2) # [1, 2, [3, 4]] list1[2].remove(3) print(list1) # [1, 2, [4], 5] print(list2) # [1, 2, [4]]