为了账号安全,请及时绑定邮箱和手机立即绑定

Python中的“无法与非整数相乘-浮点数”错误

Python中的“无法与非整数相乘-浮点数”错误

叮当猫咪 2021-03-17 13:12:52
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 totalget_average(tyler)这里发生了什么?这给我一个错误,说student[item] 无法与非整数相乘-浮点数

2 回答

?
MM们

TA贡献1886条经验 获得超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


查看完整回答
反对 回复 2021-03-23
?
慕的地10843

TA贡献1785条经验 获得超8个赞

由于您无法将列表乘以权重,因此请先获取平均值!在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


查看完整回答
反对 回复 2021-03-23
  • 2 回答
  • 0 关注
  • 407 浏览
慕课专栏
更多

添加回答

代码语言

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号