由於python中tuple與str類型是不可修改的,dict和list是可以修改的,因而在對其進行一系列修改操作的時候需千萬謹慎,其中涉及了python的assignment、copy和deepcopy一些內容。
可參考:
- https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/
- https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html
下面是一個例子,可以對比一下有無.copy()的區別
>>> dict_old = [{'a':'1'}, {'b':'2'}, {'c':'3'}]
>>> dict_new = {}
>>> list_new = []
>>> for dict_old_item in dict_old:
>>> dict_new.update(dict_old_item)
>>> list_new.append(dict_new)
>>> print(list_new)
[{'a': '1', 'b': '2', 'c': '3'},
{'a': '1', 'b': '2', 'c': '3'},
{'a': '1', 'b': '2', 'c': '3'}]
>>> dict_old = [{'a':'1'}, {'b':'2'}, {'c':'3'}]
>>> dict_new = {}
>>> list_new = []
>>> for dict_old_item in dict_old:
>>> dict_new.update(dict_old_item)
>>> list_new.append(dict_new.copy()) # 添加.copy()
>>> print(list_new)
[{'a': '1'},
{'a': '1', 'b': '2'},
{'a': '1', 'b': '2', 'c': '3'}]