一个值 | 多个值 |
---|---|
整型/浮点型/字符串 | 列表/字典/元祖/集合 |
有序 | 无序 |
---|---|
字符串/列表/元祖 | 字典/集合 |
可变 | 不可变 |
---|---|
列表/字典/集合 | 整型/浮点型/字符串 |
l1 = ['a','b','c',['d','e','f']]
l2 = l1
l1.append('g')
print(l1) # ['a','b','c',['d','e','f'],'g']
print(l2) # ['a','b','c',['d','e','f'],'g']
总结:如果l2是l1的拷贝对象,若l1内部的任意数据类型的元素变化,则l2内部的元素也会跟着改变,因为可变类型,值变id不变.
import copy
l1 = ['a','b','c'['d','e','f']]
l2 = copy.copy(l1)
l1.append('g')
print(l1) # ['a','b','c'['d','e','f'],'g']
print(l2) # ['a','b','c'['d','e','f']
l1[3].append('g')
print(l1) # ['a','b','c'['d','e','f','g'],'g']
print(l2) # ['a','b','c'['d','e','f','g']]
总结:如果l2是l1的浅拷贝对象,若l1内的不可变元素发生了改变,l2不变;如果l1内的可变元素发生了改变,则l2也会跟着改变.
import copy
l1 = ['a','b','c'['d','e','f']]
l2 = copy.deepcopy(l1)
l1.append('g')
print(l1) # ['a','b','c',['d','e','f'],'g']
print(l2) # ['a','b','c'['d','e','f']]
l1[3].append('g')
print(l1) # ['a','b','c'['d','e','f','g'],'g']
print(l2) # ['a','b','c'['d','e','f']]
总结:如果l2是l1的深拷贝对象,若l1内的不可变类型元素发生改过,l2不会变;如果l1内的可变类型元素发生了变化,l2也不会改变,即l2永远不会因为l1的变化而变化.
原文:https://www.cnblogs.com/raynduan/p/10940426.html