【问题标题】:Compute total marks and rank using dictionary in python在python中使用字典计算总分和排名
【发布时间】:2019-11-25 11:15:50
【问题描述】:

我有以下代码用于计算 Python 字典中的总分和排名。让我知道这个概念是否有任何简单的代码可用。

条件是:

  • 添加用于存储总分的新键。
  • 为排名添加新键。
  • 计算分数和排名。

    for key,value in student.items(): smark = sum(student[key]["mark"]) student[key].update({"total_marks":smark}) s=sorted(student, key = lambda x:student[x]["total_marks"], reverse=True) rank = 1 for key in s: student[key].update({"rank":rank}) rank += 1

我的输出

('a', {'rollno': 2001, 'age': 18, 'mark': [85, 65, 65], 'total_marks': 215, 'rank': 2})
('b', {'rollno': 2002, 'age': 18, 'mark': [85, 55, 65], 'total_marks': 205, 'rank': 3})
('c', {'rollno': 2003, 'age': 18, 'mark': [85, 95, 65], 'total_marks': 245, 'rank': 1})

【问题讨论】:

    标签: python-3.x dictionary dictionary-comprehension


    【解决方案1】:
    student = {}
    student["a"] = {"rollno":2001, "age":18, "mark":[85,65,65]}
    student["b"] = {"rollno":2002, "age":18, "mark":[85,55,65]}
    student["c"] = {"rollno":2003, "age":18, "mark":[85,95,65]}
    rank = {}
    for key,value in student.items():
        smark = sum(student[key]["mark"])
        student[key].update({"total_marks":smark})
    s=sorted(student, key = lambda x:student[x]["total_marks"], reverse=True)
    rank = 1
    for key in s:
        student[key].update({"rank":rank})
        rank += 1
    print("*** Rank of each student based on total marks *** \n")
    for i in student.items():
        print(i)
    

    【讨论】:

      猜你喜欢
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      相关资源
      最近更新 更多