2016-06-27 64 views
0

我有一個函數可以正常工作,但當我嘗試在另一個函數中使用它時引發了一個關鍵錯誤。我認爲只是改變德爾手[字母],這是錯誤發生的地方,而不是試圖解釋更大的上下文。在某些情況下,我可以將hand [letter]改爲hand.get(letter,None),但是我不能在del運算符中使用它,它會引發錯誤。有任何想法嗎?Python中有另一種方法可以從除del [key]以外的字典中刪除鍵值對嗎?

hand = {'r': 2, 'a': 3, 'p': 2, 'e': 1, 't': 1, 'u':1} 
word = 'rapture' 

def update_hand(hand, word): 
"""This function loops through letters, and if the letter is in the \ 
hand, it reduces the corresponding int value by one, until there is \ 
no longer that letter in the hand, then it deletes the key,value pair \ 
all together""" 
    letters = set(word) 
    for letter in letters: 
     if letter in hand.keys(): 
      hand[letter] = hand[letter]-1 
     if hand[letter] <= 0: 
      del hand[letter] 
    return hand 
+1

嘗試'pop'字典成員函數 – jmetz

回答

5

使用.pop,這樣的情況下該鍵不存在,當你使用一個默認不拋出任何錯誤,說None

hand.pop(letter, None) 
#    ^pops None when the key letter does not exist 

既然你已經擁有的支票在你的if條件之一相同的密鑰的存在,你可以簡單地做:

for letter in letters: 
    if letter in hand: # same as letter in hand.keys() 
     hand[letter] = hand[letter] - 1 
     if hand[letter] <= 0: 
      hand.pop(letter, None) # del hand[letter] should not throw errors in this case 
0

如果你的函數「,同樣可以在它自己的,但是從調用時引發另一個功能「,那麼首先要做的就是找出爲什麼在第二種情況下有問題。否則,這是一個programming by accident的典型例子 - 我們都知道它從未長期工作。

現在在您的函數的代碼中有一個明顯的原因是KeyError,它不依賴於函數的其他輸入:您試圖刪除一個密鑰而不首先檢查它是否存在(if hand[letter] <= 0:語句)。嘗試傳遞hand參數的空字典,你會發現你的功能不是而不是「工作正常」。

+0

該函數旨在假定手參數具有單詞param中的所有字母。我有另外一個函數來檢查這個單詞是否有效,也就是說,這個單詞既在單詞列表中,也僅由字母組成。這些函數通過了單元測試,這些測試是由比我更有經驗的程序員編寫的。我沒有包括這一點,因爲人們對這裏的問題太挑剔。當我嘗試將它們放在一起時,會發生有趣的事情。感謝您的反饋,我會研究它。 – sampy

相關問題