我有一个嵌套字典,用于看起来像这样的成绩簿程序(这只是一个例子,它可以是任意数量的学生或测试):
workDictionary = {'kevin': {'Test1': 97, 'Test2': 84, 'Test3': 89},
''Bob':{'Test1': 67, 'Test2': 74, 'Test3': 59},
'carol':{'Test1': 47, 'Test2': 94, 'Test3': 79},
'ted':{'Test1': 67, 'Test2': 64, 'Test3': 99}}
我想得到最里面值的平均值,例如:
finalGrade = {}
for k,v in workDictionary.iteritems():
finalGrade[k] = sum(v)/ float(len(v))
还有其他因素,我正在使用酸洗和不确定数量的学生和测试。这是完整的计划:
# Modules
import pickle
def dumpPickle(fileName):
pickle.dump(workDictionary, open(fileName,'wb'))
return
def loadUnPickle(fileName):
global workDictionary
workDictionary = pickle.load(open(fileName, 'rb'))
return(workDictionary)
workDictionary = {}
keys = workDictionary.keys()
values = workDictionary.values()
def myMenu():
mySelect = -1
while mySelect != 0:
print("\n1. Open Dictionary File\n"+
"2. Create/Write to a Dictionary\n"+
"3. Add a New Student\n"+
"4. Find a Student's Scores\n"+
"5. Add a New Student Score\n"+
"6. Display Dictionary Data\n"+
"0. Exit\n"
)
mySelect = int(input("Enter Menu Number: "))
if mySelect == 1:
fileName = input("Enter file name")
print("\nyour file is now open")
loadUnPickle(fileName)
elif mySelect == 2:
fileName = input("please create a new file.")
print("\nyour new file is now open")
elif mySelect == 3:
newStudent = input("Enter the new student's name")
firstTest = input("Enter the name of the first test")
testGrade = input("Enter the new student's first grade")
addDictionary = {newStudent:{firstTest:testGrade}}
workDictionary.update(addDictionary)
print("\n" + newStudent + str(workDictionary[newStudent]))
dumpPickle(fileName)
elif mySelect == 4:
print("\nEnter student name")
myName = input()
for name in workDictionary:
if name == myName:
print("\n",workDictionary.get(myName))
elif mySelect == 5:
print("\nEnter student name ")
myName = input()
print("\nEnter assignment to add or update")
myValue = input()
for name in workDictionary:
if name == myName:
newGrade = input("Enter new Grade")
workDictionary[name][myValue]= newGrade
dumpPickle(fileName)
print("\n" + name + str(workDictionary[name]))
elif mySelect == 6:
print(workDictionary)
return
# Main Loop
我想添加另一个菜单选项,它取一个学生的平均值并显示它。
答案 0 :(得分:0)
这是我写的,但是你可以重写它,这样你的程序会更好:
def student_avg(student):
summ = 0
grades_num = 0
for test, grade in student.items():
summ += grade
# unless you aren't sure that grade would be a int, in which case add exception
grades_num += 1
average = summ / grades_num
return average
average = student_avg(workDict["kevin"])
答案 1 :(得分:0)
您可以使用Dict理解
from statistics import mean
avg_grades = {name: mean(tests.values()) for (name, tests) in workDictionary.items()}
存储在avg_grades中的结果将是:
{'Bob': 66.66666666666667,
'carol': 73.33333333333333,
'kevin': 90.0,
'ted': 76.66666666666667}