拷贝、浅拷贝、深拷贝解答
拷贝
拷贝/浅拷贝/深拷贝都是针对可变类型数据而言的
list1 = ["a","b","c","d","f",["e","f","g"]]
list2 = list1
list1[2] = "plf"
list1[5][0] = "lt"
print(list1)
print(list2)
'''
['a', 'b', 'plf', 'd', 'f', ['lt', 'f', 'g']]
['a', 'b', 'plf', 'd', 'f', ['lt', 'f', 'g']]
'''
'''
总结: 如果list2是 list1的拷贝,那么list1和list2公用一块内存空间,因此list1改变,list2也会随着改变!
'''
浅拷贝
import copy
list1 = ["a","b","c","d","f",["e","f","g"]]
list2 = copy.copy(list1)
list1[2] = "plf"
list1[5][0] = "lt"
list1[5].append("xyz")
print(list1)
print(list2)
'''
['a', 'b', 'plf', 'd', 'f', ['lt', 'f', 'g', 'xyz']]
['a', 'b', 'c', 'd', 'f', ['lt', 'f', 'g', 'xyz']]
'''
'''
总结:
1. 如果 list2 是 list1 的浅拷贝对象,则1内的不可变元素发生了改变,list2 不变;
2. 如果 list1 内的可变元素发生了改变,则 list2 会跟着改变.
'''
深拷贝
import copy
list1 = ["a","b","c","d","f",["e","f","g"]]
list2 = copy.deepcopy(list1)
list1[2] = "plf"
list1[5][0] = "lt"
list1[5].append("xyz")
print(list1)
print(list2)
'''
['a', 'b', 'plf', 'd', 'f', ['lt', 'f', 'g', 'xyz']]
['a', 'b', 'c', 'd', 'f', ['e', 'f', 'g']]
'''
'''
总结:
如果list2 是 list1 的深拷贝,那么list1 和list2 都是独立的个体,不存在任何关系
'''