【问题标题】:How to get thigs out from list of dictionaries如何从字典列表中取出东西
【发布时间】:2021-03-20 10:23:57
【问题描述】:

我在从字典列表中取出内容时遇到了一些问题。

  1. 我想从所有学校科目中找到平均成绩最好的学生,并且函数需要返回平均成绩最好的学生 ID
  2. 从数学中找到最佳平均值并返回具有最佳平均值的学生 ID 的函数
  3. 计算所有学生成绩的函数

我完成了第三个任务,但现在我有点卡在 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


【解决方案1】:

为您的第一个函数(最好的总体平均学生)和第二个函数(最好的数学平均值)尝试这个(抱歉,对齐无法在堆栈溢出时正确对齐):-(如果有任何问题,请告诉我)

def funct1andfunt2(students):# students is your list of dictionaries
bestmathsaverage=[0,0]#at 1st element is index of student and 2nd element is the average
bestoverallaverage=[0,0]#at 1st element is index of student and 2nd element is the average
for i in range(len(students)):
    studentsmathaverage=sum(students[i]["math"])/len(students[i]["math"])
    if bestmathsaverage[1]<studentsmathaverage:
        bestmathsaverage[0],bestmathsaverage[1]=i,studentsmathaverage
    studentsoverallaverage=sum(students[i]["english"])/len(students[i]["english"])
    studentsoverallaverage+=sum(students[i]["history"])/len(students[i]["history"])
    studentsoverallaverage+=studentsmathaverage
    if bestoverallaverage[1]<studentsoverallaverage:
        bestoverallaverage[0],bestoverallaverage[1]=i,studentsoverallaverage
return bestmathsaverage,bestoverallaverage
 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2021-07-20
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多