我对函数的实现有疑问。
目的是减少字典中某个键的值(如果它在单词中)。例如:
word = hi
hand = {'h':2,'i':1}
-> 函数 update_hand(字,手)
hand = {'h'1}
所以我尝试了:
def update_hand(hand, word):
for letter in range(len(word)):
if hand.get(word[letter],0) != 0:
hand[word[letter]] -= 1
if hand.get(word[letter],0) == 0:
del hand[word[letter]]
return hand
但是当我调用它时,我得到:
Traceback (most recent call last):
File "/home/phillip/Desktop/ps3/ps3/ps3a.py", line 168, in <module>
print update_hand('quali', {'a': 1, 'i': 1, 'm': 1, 'l': 2, 'q': 1, 'u': 1})
File "/home/phillip/Desktop/ps3/ps3/ps3a.py", line 162, in update_hand
if hand.get(word[letter],0) != 0:
AttributeError: 'str' object has no attribute 'get'
所以我试图在一个测试文件中实现它(只是用于战利品)并且一切正常......好吧,我不知道我做错了什么。
谢谢,菲利普