2013-03-08 146 views
-1

我是編碼方面的新手,我無法正確使用此功能。無法比較字典值

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:列表索引必須是整數,而不是str」。有人可以解釋我出錯的地方嗎?

+2

什麼是'手'?這很可能是一個列表,而不是一個字典。向我們展示處理「手」的代碼。 – 2013-03-08 13:49:18

+0

哪一行產生錯誤? – thegrinner 2013-03-08 13:50:21

+0

@thegrinner# – asheeshr 2013-03-08 13:51:23

回答

1

你的問題肯定是這一行:

if wordDic[letter] > hand[letter]: 

而問題是,letter是你使用到該索引字符(str)您hand(這顯然是一個list,而不是作爲dict你期望)。

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