迭代字典:获取'NoneType'对象不是可迭代错误

时间:2010-09-02 19:16:32

标签: python dictionary iteration

功能类:

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行对应于'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 个答案:

答案 0 :(得分:4)

这意味着变量wordDictNone而不是字典。这意味着调用play_best_hand的函数出错。可能您忘记return函数中的值,因此返回None

答案 1 :(得分:2)

play_best_hand()函数中:

if wordDict[word] > points:
    bestWord == word

你可能打算做一个作业,而不是比较相等:

if wordDict[word] > points:
    bestWord = word