[英]Preventing Python dictionary from mutating
我需要編寫一個函數,該函數將a字典和一個字符串作為輸入,並返回更新的字典,如下所示:
>>> dct = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
>>> updateHand(dct, 'quail')
returns {'a':0, 'q':0, 'l':1, 'm':1, 'u':0, 'i':0}
我正在寫下面的代碼,但是我不知道它會怎樣改變字典(不應該)。
def updateHand(dct, s)
for char in s :
dct[char] = dct.get(char,0) - 1
return dct
當我運行上面的示例時,我收到以下消息:
Original dct was {'a': 1, 'i': 1, 'm': 1, 'l': 2, 'q': 1, 'u': 1}
but implementation of updateHand mutated the original hand!
Now the dct looks like this: {'a': 0, 'q': 0, 'u': 0, 'i': 0, 'm': 1, 'l': 1}
突變字典是什么意思? 我該如何克服呢?
另外,Python是否不維護Java等元素的隨機順序?
使用dict.copy
使用原始字典的副本:
def updateHand(dct, s)
dct = dct.copy() # <----
for char in s :
dct[char] = dct.get(char,0) - 1
return dct
突變字典是什么意思?
該代碼更改了傳遞的字典,而不是返回新的字典。
另外,Python是否不維護Java等元素的隨機順序?
字典中不保留插入順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.