【问题标题】:Iterate over Dictionary: Get 'NoneType" object is not iterable error遍历字典:获取“NoneType”对象不是可迭代错误
【发布时间】:2010-09-02 19:16:32
【问题描述】:

函数类:

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

【问题讨论】:

    标签: python dictionary iteration


    【解决方案1】:

    这意味着变量wordDictNone 而不是字典。这意味着调用play_best_hand 的函数中存在错误。可能,你忘记在函数中return 一个值,所以它返回None

    【讨论】:

    • 在我开始打猎后得到了修复!谢谢!
    【解决方案2】:

    play_best_hand() 函数中你有:

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

    您可能打算做一个分配而不是比较是否相等:

    if wordDict[word] > points:
        bestWord = word
    

    【讨论】:

    • @Noah Clark:即使纠正了这一点,bestword 在返回之前也可能没有设置为任何内容。 (例如,如果wordDict 为空或hand 为空字符串,则会发生这种情况。)
    猜你喜欢
    • 2021-04-25
    • 2019-01-10
    • 2011-12-13
    • 2016-09-11
    • 2014-10-09
    • 2013-12-01
    • 2021-08-20
    • 1970-01-01
    • 2013-06-03
    相关资源
    最近更新 更多