迭代字典时出现“NoneType”对象不可迭代错误
这是一个函数类:
def play_best_hand(hand, wordDict):
tempHand = hand.copy()
points = 0
for word in wordDict:
for letter in word:
if letter in hand:
tempHand[letter] = tempHand[letter] - 1
if tempHand[letter] < 0:
return False
if wordDict[word] > points:
bestWord == word
points = wordDict[word]
return bestWord
这是我的错误追踪信息。第209行对应的是'for word in wordDict'这一行。
Traceback (most recent call last):
File "ps6.py", line 323, in <module>
play_game(word_list)
File "ps6.py", line 307, in play_game
play_hand(hand.copy(), word_list)
File "ps6.py", line 257, in play_hand
guess = play_best_hand(hand, wordDict)
File "ps6.py", line 209, in play_best_hand
for word in wordDict:
TypeError: 'NoneType' object is not iterable
2 个回答
2
在 play_best_hand()
这个函数里,你写了:
if wordDict[word] > points:
bestWord == word
你可能是想要进行赋值,而不是在比较是否相等:
if wordDict[word] > points:
bestWord = word
4
这句话的意思是,变量 wordDict
现在是 None
,而不是一个字典。这说明在调用 play_best_hand
的函数里出现了错误。可能是你在某个函数里忘记了 return
一个值,所以它返回了 None
?