我为我的大学CS课分配了这个问题。总的来说,它在字典和集合以及编码方面还是新的。 所以我正在为将userInput分配给字典的部分寻找一种更pythonic的方式。这可以满足我的需求,但除此之外,它会变得乏味。 是的,我从CodeAcademy看到了与此功能类似的其他问题,但这些问题没有我的问题的答案。 预先感谢您的任何投入。保重。
gradeBook = {
"student1" : {
"name": "Andy",
"homework": [90.0, 85.0, 78.0, 92.0],
"quizzes": [85.0, 87.0, 90.0, 75.0, 95.0],
"tests": [85.0, 65.0]
},
"student2" : {
"name": "Brad",
"homework": [88.0, 78.0, 86.0, 99.0],
"quizzes": [88.0, 82.0, 100.0, 74.0, 82.0],
"tests": [90.0, 92.0]
},
"student3" : {
"name": "Billy",
"homework": [81.0, 79.0, 80.0, 50.0],
"quizzes": [80.0, 78.0, 95.0, 80.0, 84.0],
"tests": [95.0, 93.0]
}}
for k, v in gradeBook.items():
print()
for k in v:
print(k + ':', v[k])
print()
userInput = input("Which students' average would you like to view: \nAndy, Brad, or Billy? \n")
print()
#assigning userInput to a students dictionary
if userInput == "Andy":
userInput1 = gradeBook["student1"]["homework"]
userInput2 = gradeBook["student1"]["quizzes"]
userInput3 = gradeBook["student1"]["tests"]
elif userInput == "Brad":
userInput1 = gradeBook["student2"]["homework"]
userInput2 = gradeBook["student2"]["quizzes"]
userInput3 = gradeBook["student2"]["tests"]
else:
userInput1 = gradeBook["student3"]["homework"]
userInput2 = gradeBook["student3"]["quizzes"]
userInput3 = gradeBook["student3"]["tests"]
def get_average(userInput):
averageHW = sum(userInput1) / len(userInput1)
averageQ = sum(userInput2) / len(userInput2)
averageT = sum(userInput3) / len(userInput3)
print(averageHW, averageQ, averageT) #normal average
wAverageHW = averageHW * 0.10
wAverageQ = averageQ * 0.30
wAverageT = averageT * 0.60
print(wAverageHW, wAverageQ, wAverageT) #weighted average
get_average(userInput)
答案 0 :(得分:0)
如果您要按学生姓名进行查找,则需要重新输入字典的密码。
gradebookByStudent = {gradebook[k][‘name’]: gradebook[k] for k in gradebook}
#get your student name via user input
print(‘HW average is: ‘ + mean(gradebookByStudent[userInput][‘homework’]))
这使您可以查询O(log(n))最坏的情况,即遍历字典时的平均值O(1)与O(n),可节省大量时间。
答案 1 :(得分:0)
您可以使用元组拆包法来遍历字典
for key, student in gradebook.items():
If student ['name'] == userinput:
getaverage(student)
类似这样的东西更像pythonic,使您可以同时浏览字典的键和值部分