一个易犯的错误,关于 Python 的传值(对于不可变量) 和 传引用(对于可变量),浅拷贝和深拷贝。废话不多说,看例子,
直接改变可变字典值,失败,
>>> dic = dict.fromkeys(range(5), []) >>> dic {0: [], 1: [], 2: [], 3: [], 4: []} >>> dic[0] [] >>> dic[0].append(123) >>> dic {0: [123], 1: [123], 2: [123], 3: [123], 4: [123]} >>>
间接改变可变字典值,失败。
>>> dic = dict.fromkeys(range(5), []) >>> dic {0: [], 1: [], 2: [], 3: [], 4: []} >>> v = dic[0] >>> v [] >>> v.append(123) >>> v [123] >>> dic {0: [123], 1: [123], 2: [123], 3: [123], 4: [123]}
切片浅拷贝,对于非嵌套可变字典值,赋单值,成功,
>>> dic = dict.fromkeys(range(5), []) >>> dic {0: [], 1: [], 2: [], 3: [], 4: []} >>> v = dic[0][:] >>> v [] >>> v.append(123) >>> v [123] >>> dic {0: [], 1: [], 2: [], 3: [], 4: []} >>> >>> dic[0] = v >>> dic {0: [123], 1: [], 2: [], 3: [], 4: []}
切片浅拷贝,对于非嵌套可变字典值,赋可变列表,成功,
>>> dic = dict.fromkeys(range(5), []) >>> dic {0: [], 1: [], 2: [], 3: [], 4: []} >>> v = dic[0][:] >>> v.append([1, 2, 3]) >>> v [[1, 2, 3]] >>> >>> dic[0] = v >>> dic {0: [[1, 2, 3]], 1: [], 2: [], 3: [], 4: []}
copy.copy 浅拷贝,成功,
>>> dic = dict.fromkeys(range(5), []) >>> dic {0: [], 1: [], 2: [], 3: [], 4: []} >>> >>> v = copy.copy(dic[0]) # shallow copy >>> v [] >>> v.append([1, 2, 3]) >>> v [[1, 2, 3]] >>> >>> dic[0] = v >>> dic {0: [[1, 2, 3]], 1: [], 2: [], 3: [], 4: []} >>>
copy.deepcopy 深拷贝,成功,这个最靠谱。
>>> dic = dict.fromkeys(range(5), []) >>> dic {0: [], 1: [], 2: [], 3: [], 4: []} >>> >>> v = copy.deepcopy(dic[0]) >>> v [] >>> v.append([1, 2, 3]) >>> v [[1, 2, 3]] >>> >>> dic[0] = v >>> dic {0: [[1, 2, 3]], 1: [], 2: [], 3: [], 4: []} >>>
完。