나는 독자적으로 잘 작동하는 함수를 가지고 있지만 다른 함수 내에서 사용하려고 할 때 중요한 오류가 발생합니다. 큰 문맥을 설명하기보다는 오류가 발생한 부분 인 손 [문자]을 변경하는 것이 더 쉬울 것이라고 생각했습니다. 어떤 경우에는 hand [letter]를 hand.get (letter, None)로 바꿀 수 있지만 del 연산자와 함께 사용할 수는 없으므로 오류가 발생합니다. 어떤 아이디어? 키가 당신이 기본값을 사용하는 경우,이 오류가 발생하지 않는 존재하지 않는 경우에, 그래서파이썬에서 del 키 [value]가 아닌 사전에서 값 쌍을 제거하는 또 다른 방법이 있습니까?
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
'pop' 사전 멤버 함수를 사용하십시오 – jmetz