python 赋值 浅拷贝 深拷贝

参考:https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html

  • 赋值:变量直接指向对象
ls = [i for i in range(0,10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
lss = ls # [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
for idx,v in enumerate(lss):
    lss[idx] = 10
lss # [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
ls # [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
  • 浅拷贝:只拷贝父对象,不会拷贝对象中的子对象(而是引用地址)
ls = [[0,0,0], 1, 2, 3, 4, 5, 6, 7, 8, 9]
lss = ls.copy() # [[0,0,0], 1, 2, 3, 4, 5, 6, 7, 8, 9]
for idx in range(1,len(ls)):
    lss[idx] = 10
lss[0].append(99)
ls # [[0, 0, 0], 1, 2, 3, 4, 5, 6, 7, 8, 9]
lss #  [[0, 0, 0, 99], 10, 10, 10, 10, 10, 10, 10, 10, 10]

需要注意的是,

ls = [[0,0,0], 1, 2, 3, 4, 5, 6, 7, 8, 9]
lss = ls.copy() # [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
for idx in range(1,len(ls)):
    lss[idx] = 10

# 这里又做了一次浅拷贝,所以不会影响值    
for i in lss[0]:
    i = 99
ls # [[0, 0, 0], 1, 2, 3, 4, 5, 6, 7, 8, 9]
lss # [[0, 0, 0], 10, 10, 10, 10, 10, 10, 10, 10, 10]
  • 深拷贝:完全拷贝,不会对原变量产生影响
ls = [[0,0,0], 1, 2, 3, 4, 5, 6, 7, 8, 9]
lss = ls.copy() # [[0,0,0], 1, 2, 3, 4, 5, 6, 7, 8, 9]
for idx in range(1,len(ls)):
    lss[idx] = 10
lss[0].append(99)
ls # [[0, 0, 0], 1, 2, 3, 4, 5, 6, 7, 8, 9]
lss # [[0, 0, 0, 99], 10, 10, 10, 10, 10, 10, 10, 10, 10]

你可能感兴趣的:(python 赋值 浅拷贝 深拷贝)