我在大学CS课上被分配了这个问题。在字典、集合和一般编码中仍然是新的。因此,我正在为将userInput分配给字典的部分寻找一种更像蟒蛇的方式。这可以满足我的需求,但除此之外,任何事情都会变得乏味。是的,我已经从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)
您可以使用元组拆包来通过字典进行itteratefor key, student in gradebook.items():
If student ['name'] == userinput:
getaverage(student)
像这样更像蟒蛇的东西允许你同时浏览字典的键和值部分
如果要按学生姓名进行查找,则需要重新键入词典。
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(,这显著节省了时间。