&引用;不能';t乘以非整数-浮点;Python中的错误
这是怎么回事?我这样说是不对的&引用;不能';t乘以非整数-浮点;Python中的错误,python,Python,这是怎么回事?我这样说是不对的 student[item]无法与非整数浮点相乘 您试图将字符串和列表与浮点数相乘,这是不可能的 lloyd = { "name": "Lloyd", "homework": [90, 97, 75, 92], "quizzes": [88, 40, 94], "tests": [75, 90] } alice = { "name": "Alice", "homework": [100, 92, 98, 100],
student[item]
无法与非整数浮点相乘
您试图将字符串和列表与浮点数相乘,这是不可能的
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] * weight
因为你不能将列表乘以权重,所以先得到平均值!在for循环中添加以下行:
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
averaged = sum(student[item])/float(len(student[item]))
total += averaged * weight
现在这是您的for循环:
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
averaged = sum(student[item])/float(len(student[item]))
total += averaged * weight
尝试添加一些打印语句,以便查看发生了什么这是错误的,您正在尝试对字符串执行
sum
(student[“name”]
是一个字符串)