Python"' builtin_function_or_method'对象没有属性' __ getitem __'"错误

时间:2016-12-28 04:53:36

标签: python-3.x

我在下面编写了一个python代码,它定义了一个函数,该函数返回给定字符串的拼字游戏分数:

score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, 
             "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, 
             "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, 
             "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, 
             "x": 8, "z": 10}

def scrabble_score(word):
    word1 = (word).lower
    list_a = []
    list_b = range(len(word))
    for i in list_b:
        list_a[i] = word1[i]
    total = 0 
    for i in list_a:
        score  = int(score[i])
        total += score
    return str(total)

上面的代码有什么问题?我得到的错误是: ' builtin_function_or_method'对象没有属性' getitem '

2 个答案:

答案 0 :(得分:2)

使用__getitem__访问元素时会调用

[]

执行word1 = (word).lower后,您要将word1分配给函数lower。相反,你应该调用函数(即word.lower())。

当Python看到word1[i]时,它会尝试访问第i个索引处的元素,但由于word1是函数而不是字符串,因此Python会感到困惑。

答案 1 :(得分:0)

score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2, 
         "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3, 
         "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1, 
         "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4, 
         "x": 8, "z": 10}

def scrabble_score (word):

    word=word.lower()

    total=0
    for char in word:
       if char in score:
        total =total+ score[char]
    return total    

print (scrabble_score('xenophobia') )