代码简述:函数返回字典覆盖所有字典
主代码首先制作一个空白的字典,它传递给我的函数。该函数记录每个数字的数量并更新随后返回的字典。然而,当函数执行时,它会将输入的'blank_dictionary'覆盖为它返回的字典('new_dictionary')。为什么会发生?我希望主代码中的'字典'始终保持空白,以便可以重复使用。
def index_list(lst, blank_dictionary):
new_dictionary = blank_dictionary
for i in lst:
new_dictionary[i] += 1
return new_dictionary
number = 1
maximum = 3
numbers = range(1,maximum+1)
dictionary = {}
for i in numbers:
dictionary[i] = 0
print ('original blank dictionary', dictionary)
new_dictionary = index_list([3,3,3],dictionary)
print ('new dictionary which indexed the list', new_dictionary)
print ('should still be blank, but isnt', dictionary)
输出:
original blank dictionary {1: 0, 2: 0, 3: 0}
new dictionary which indexed the list {1: 0, 2: 0, 3: 3}
should still be blank, but isnt {1: 0, 2: 0, 3: 3}
非常感谢
[如何复制字典并仅编辑副本]的可能副本(http://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy ) –
是的,谢谢@PierPaolo。 – PurpleDiane
[阅读Python中如何使用变量和赋值。](https://nedbatchelder.com/text/names.html) – user2357112