代碼簡述:函數返回字典覆蓋所有字典
主代碼首先製作一個空白的字典,它傳遞給我的函數。該函數記錄每個數字的數量並更新隨後返回的字典。然而,當函數執行時,它會將輸入的'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