无法比较字典值

时间:2013-03-08 13:48:03

标签: python python-2.7

我对编码很陌生,而且我无法正常使用此功能。

def isValidWord(word, hand, wordList):
    """
    Returns True if word is in the wordList and is entirely
    composed of letters in the hand. Otherwise, returns False.

    Does not mutate hand or wordList.

    word: string
    hand: dictionary (string -> int)
    wordList: list of lowercase strings
    """
    wordDic = {}
    if word not in wordList:    
        return False   
    for letter in word:
        if letter in wordDic:
            wordDic[letter] += 1
        else:
            wordDic[letter] =  1
    if wordDic[letter] > hand[letter]: # 
        return False
    return True

我要做的是比较wordDic中字母出现次数的字典值以及它在手中出现的次数。但我一直得到“TypeError:list indices必须是整数,而不是str”。有人可以解释我哪里出错了吗?

2 个答案:

答案 0 :(得分:1)

你的问题肯定是这一行:

if wordDic[letter] > hand[letter]:

问题是letter是一个字符(str),您用它来为hand(显然是list而不是{dict编制索引{1}}正如您所期望的那样。)

答案 1 :(得分:1)

问题是hand(可能)是一个列表,而不是字典,而您尝试使用letter str来访问它。无法使用字符串索引列表,因此TypeError

有关详情,请参阅列表上的Python documentation


hand绝对是一个列表。测试代码:

>>> l = [1,2]
>>> l['a']
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    l['a']
TypeError: list indices must be integers, not str