2013-05-12 715 views
0
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) 

這是怎麼回事?這是給我的錯誤,指出Python中的「不能乘以非整數 - 浮點數」錯誤

student[item]不能由一個非整數相乘 - 浮

+0

嘗試加入一些打印語句所以你可以看到正在發生的事情 – datguy 2013-05-12 03:48:55

回答

1

你試圖乘字符串和列表與浮點數這是不可能的。

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 
0

因爲你無法通過重量乘以名單,第一個獲得平均!添加在您的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 
+0

這是不對的,你」重新嘗試在字符串上執行'sum'('student [「name」]'是一個字符串) – 2013-05-12 05:14:04