weixin_46895913
2020-11-19 22:31
采纳率: 100%
浏览 264
已结题

python成绩字典按平均分排序

python字典排序:现有4门课的成绩字典如下所示。统计每个人的平均成绩,并根据平均成绩进行排序。要求按姓名检索平均成绩和排名
grade1={'刘达':89,'王尔':95,'李珊':67,'陈思':75}
grade2={'刘达':75,'王尔':79,'李珊':79}
grade3={'李珊':87,'陈思':91,'张悟':75}
grade4={'刘达':89,'王尔':86,'张悟':99}

例如:

输入:陈思

输出为:陈思的成绩为83,排名第4

  • 收藏

1条回答 默认 最新

  • wAIxiSeu 2020-11-20 15:57
    已采纳
    from collections import Counter
    grade1={'刘达':89,'王尔':95,'李珊':67,'陈思':75}
    grade2={'刘达':75,'王尔':79,'李珊':79}
    grade3={'李珊':87,'陈思':91,'张悟':75}
    grade4={'刘达':89,'王尔':86,'张悟':99}
    k = Counter(grade1.keys()) + Counter(grade2.keys()) + Counter(grade3.keys()) + Counter(grade4.keys())
    t = Counter(grade1) + Counter(grade2) + Counter(grade3) + Counter(grade4)
    average = sorted({_k: t[_k]//_v for _k,_v in k.items()}.items(), key=lambda _s: _s[1], reverse=True)
    grades = {_a[0]: (_i+1, _a[1]) for _i, _a in enumerate(average)}
    print('陈思的成绩为{},排名第{}'.format(grades['陈思'][1], grades['陈思'][0]))
    已采纳该答案
    2 打赏 评论

相关推荐 更多相似问题