Dict是一种特殊的数据类型,一个Dict变量的数值传递给其它变量时,并未复制内容交给其它变量,而是仅传递Dict变量的内存地址。所以当Dict变量值发生改变时,所赋值的变量内容随之一起变化,如下代码所示:
a_list = []
a = {1:'a',2:'b',3:'c'}
a_list.append(a)
a = {1:'x',2:'y',3:'z'}
a_list.append(a)
print(a_list)
#结果如下:
# [{1: 'a', 2: 'b', 3: 'c'}, {1: 'x', 2: 'y', 3: 'z'}]
#
#采取单个元素独立赋值,将触发地址(指针)传递机制
a_list =[]
a[1] = 10
a[2] = 20
a[3] = 30
a_list.append(a)
a[1] = 11
a[2] = 12
a[3] = 13
a_list.append(a)
print(a_list)
#结果如下:
# [{1: 11, 2: 12, 3: 13}, {1: 11, 2: 12, 3: 13}]
#
# 而不是所期望的:
# [{1: 10, 2:20, 3: 30}, {1: 11, 2: 12, 3: 13}]
#
为改变上述状况,原dict值变化,不再影响已经赋值对象,采取浅层拷贝与深拷贝两种策略:
浅层拷贝:temp = a.copy()
深层拷贝:temp = a.deepcopy()
同理:append的对象是list,也采取单独赋值的机制,也将出现类似上述现象:
alist = []*3
alist[0] = 1
alist[1] = 2
alist[2] = 3
aalist = []
aalist.append(alist)
print(aalist)
#结果如下:alist = [1, 2, 3]
#
alist[0] = 11
alist[1] = 22
alist[2] = 33
aalist.append(alist)
print(aalist)
#结果如下:alist = [[11,22,33],[11,22,33]]
#而非所期待的:[[1,2,3], [11,22,33]]