python:深拷贝与浅拷贝

时间:2022-06-01 20:54:43
import copy
name = ["sams", ["su", "ca"]]
name0 = name#直接复制,指向同一内存空间
name1 = copy.copy(name)#浅拷贝,也可以写作name1 = name[:]
name2 = copy.deepcopy(name)#深拷贝
name[0] = "son"
name[1][0] = "qi"
print(name,"\n",name0,"\n",name1,"\n",name2)

结果:

 ['son', ['qi', 'ca']]
 ['son', ['qi', 'ca']]
 ['sams', ['qi', 'ca']]
 ['sams', ['su', 'ca']]