错误:列表索引必须是整数而不是浮点数

Roo*_*ner 3 python python-2.7

下面的代码应该从学生的字典中获取标记列表并计算学生的平均分数.我得到"TypeError:list indices必须是整数,而不是float"错误.

alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}

# Averege function is given below for calculating avg
def average(lst):
    l=float(len(lst))
    total = 0.0
    #code works till here the error occoured below
    for item in lst:
        add = int(lst[item])
        print add
        total+=add
    return total//l

print average(alice['tests'])
print alice['tests']
Run Code Online (Sandbox Code Playgroud)

小智 5

问题出在这一行:

for item in lst:
    add = int(lst[item])
Run Code Online (Sandbox Code Playgroud)

for item in lst遍历item列表中的每个,而不是索引.item列表中的浮点值也是如此.而是试试这个:

for item in lst:
    add = int(item)
Run Code Online (Sandbox Code Playgroud)

此外,没有理由强制转换为整数,因为这会使您的平均值变得混乱,因此您可以将其进一步缩短为:

for item in lst:
    add = item
Run Code Online (Sandbox Code Playgroud)

这意味着for循环可以简化为:

for item in lst:
    total+= item
Run Code Online (Sandbox Code Playgroud)

这意味着我们可以使用sum内置的进一步缩短它:

total = sum(lst)
Run Code Online (Sandbox Code Playgroud)

由于total现在是浮点数,我们不需要使用双斜杠指定浮点除法,我们不再需要将长度转换为浮点数,因此函数变为:

def average(lst):
    l=len(lst)
    total = sum(lst)
    return total/l
Run Code Online (Sandbox Code Playgroud)

最后,没有理由不在一条容易理解的行上做到这一点:

def average(lst):
    return sum(lst)/len(lst)
Run Code Online (Sandbox Code Playgroud)