Python中的“不能乘以非整数浮点”错误

2024-04-26 21:13:56 发布

您现在位置:Python中文网/ 问答频道 /正文

lloyd = {
    "name": "Lloyd",
    "homework": [90, 97, 75, 92],
    "quizzes": [88, 40, 94],
    "tests": [75, 90]
}
alice = {
    "name": "Alice",
    "homework": [100, 92, 98, 100],
    "quizzes": [82, 83, 91],
    "tests": [89, 97]
}
tyler = {
    "name": "Tyler",
    "homework": [0, 87, 75, 22],
    "quizzes": [0, 75, 78],
    "tests": [100, 100]
}

def get_average(student):
    weight = 0
    total = 0
    for item in student:
        if item == "homework":
            weight = .1
        elif item == "quizzes":
            weight = .3
        elif item == "tests":
            weight = .6
        else:
            weight = 0
        total += student[item] * weight

    return total

get_average(tyler)

这是怎么回事?我这样说是不对的

student[item] couldn't be multiplied by an non integer - float


Tags: namegettestsitemstudenttotalaveragehomework
2条回答

你试图用浮点数来乘法字符串和列表,这是不可能的。你知道吗

student[item] * weight

尝试以下操作:

def get_average(student):
    weight = 0
    total = 0
    for item,val in student.items(): #use dict.items() if you need to wrk on both key and values
        if item == "homework":
            weight = .1
        elif item == "quizzes":
            weight = .3
        elif item == "tests":
            weight = .6
        else:
            continue    # no need of weight = 0 simple move on to next item
                        # continue statement jumps the loop to next iteration
        total += (float(sum(val)) / len(val)) * weight
    return total

print get_average(tyler)  #prints 79.9

因为你不能把单子乘以重量,所以先得到平均数!在for循环中添加以下行:

averaged = sum(student[item])/float(len(student[item]))
total += averaged * weight

现在这是for循环:

for item in student:
        if item != "Name":
            averaged = sum(student[item])/float(len(student[item]))
        if item == "homework":
            weight = .1
        elif item == "quizzes":
            weight = .3
        elif item == "tests":
            weight = .6
        else:
            weight = 0
        total += averaged * weight

相关问题 更多 >