【发布时间】:2021-03-20 10:23:57
【问题描述】:
我在从字典列表中取出内容时遇到了一些问题。
- 我想从所有学校科目中找到平均成绩最好的学生,并且函数需要返回平均成绩最好的学生 ID
- 从数学中找到最佳平均值并返回具有最佳平均值的学生 ID 的函数
- 计算所有学生成绩的函数
我完成了第三个任务,但现在我有点卡在 1,2 分上。我不知道我应该如何取出学生的平均成绩并打印出来。
非常感谢帮助/提示。 PS:我不想只使用“列表理解”循环。 代码如下
students = [
{
"id":1,
"math":[1,4,3,4,2],
"english":[2,2,4,3,2,1,1],
"history":[4,1,2,5,5]
},
{
"id":2,
"math":[1,1,5,4,2],
"english":[5,5,3,4,2,1,5,5],
"history":[3,3,3,4,5,1]
},
{
"id":3,
"math":[1,2,1,3,4,3],
"english":[1,3,3,2,3,3,3],
"history":[3,3,3,4,5,1]
},
{
"id":4,
"math":[3,3,3,2,1],
"english":[4,4,3,3,4,5,5],
"history":[1,2,2,3,4,4]
},
]
def average(value):
return round(sum(value) / len(value), 2)
def all_students_average(student):
class_scores = []
for student in students:
for k, v in student.items():
if k in ["math", "english", "history"]:
for score in v:
class_scores.append(score)
average_grades = average(class_scores)
print(average_grades)
def math_students_average(student):
math_scores = []
for student in students:
for k, v in student.items():
if k in ["math"]:
for score in v:
math_scores.append(score)
average_math = average(math_scores)
maximum = max(math_scores)
print(maximum)
math_students_average(students)
all_students_average(students)
【问题讨论】:
-
创建一个新字典,遍历所有学生字典。使用学生 ID 作为键并将平均分数存储为值。循环遍历整个新字典并从项目中找到最高的键值对......只是一种方法 - 你的问题到底是什么
标签: python-3.x list dictionary