【发布时间】:2017-09-19 18:30:36
【问题描述】:
代码简要说明:
主代码首先创建一个空白字典,然后将其传递给我的函数。该函数计算每个数字的数量并更新然后返回的字典。但是,当函数执行时,它会将输入“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}
非常感谢
【问题讨论】:
-
是的,谢谢@PierPaolo。
标签: python function dictionary overwrite