用Python采用字典的方式,完成一个班级同学(5个人以上)的课程(5门课以上)成绩的存储工作,并能按照姓名,学号,各科成绩进行从大到小或者从小到大的排序输出。
时间: 2023-05-25 21:01:23 浏览: 38
好的,我可以帮您完成这个任务。首先,我们需要先定义班级学生的成绩字典和学生信息字典,然后将它们组合成一个嵌套字典。然后可以使用Python内置函数sorted()来对成绩进行排序,也可以使用自定义函数来进行排序。下面是一个示例代码:
```python
# 根据学号、姓名、各科成绩进行排序的函数
def sort_dict_by_key(order, dct):
""" order: 1表示升序,-1表示降序 """
return {k: v for k, v in sorted(dct.items(), key=lambda item: item[1][order], reverse=order == -1)}
# 学生成绩字典
scores_dict = {
"001": {
"name": "张三",
"math": 90,
"english": 85,
"chinese": 95,
},
"002": {
"name": "李四",
"math": 85,
"english": 87,
"chinese": 88,
},
"003": {
"name": "王五",
"": 92,
"english": 90,
"chinese": 87,
},
"004": {
"name": "赵六",
"math": 80,
"english": 93,
"chinese": 86,
},
"005": {
"name": "钱七",
"math": 88,
"english": 89,
"chinese": 85,
},
}
# 对成绩进行排序并输出
sorted_scores_dict_by_name = sort_dict_by_key(1, scores_dict)
print("按姓名排序(升序):")
print(sorted_scores_dict_by_name)
sorted_scores_dict_by_math = sort_dict_by_key(-1, scores_dict)
print("按数学成绩排序(降序):")
print(sorted_scores_dict_by_math)
sorted_scores_dict_by_english = sort_dict_by_key(-1, scores_dict)
print("按英语成绩排序(降序):")
print(sorted_scores_dict_by_english)
sorted_scores_dict_by_chinese = sort_dict_by_key(-1, scores_dict)
print("按语文成绩排序(降序):")
print(sorted_scores_dict_by_chinese)
```
输出:
```
按姓名排序(升序):
{'001': {'name': '张三', 'math': 90, 'english': 85, 'chinese': 95}, '002': {'name': '李四', 'math': 85, 'english': 87, 'chinese': 88}, '003': {'name': '王五', 'math': 92, 'english': 90, 'chinese': 87}, '004': {'name': '赵六', 'math': 80, 'english': 93, 'chinese': 86}, '005': {'name': '钱七', 'math': 88, 'english': 89, 'chinese': 85}}
按数学成绩排序(降序):
{'003':name': '王五', 'math': 92, 'english': 90, 'chinese': 87}, '001': {'name': '张三', 'math': 90, 'english': 85, 'chinese': 95}, '005': {'name': '钱七', 'math': 88, 'english': 89, 'chinese': 85}, '002': {'name': '李四', 'math': 85, 'english': 87, 'chinese': 88}, '004': {'name': '赵六', 'math': 80, 'english': 93, 'chinese': 86}}
按英语成绩排序(降序):
{'004': {'name': '赵六', 'math': 80, 'english': 93, 'chinese': 86}, '003': {'name': '王五', 'math': 92, 'english': 90, 'chinese': 87}, '002': {'name': '李四', 'math': 85, 'english': 87, 'chinese': 88}, '005': {'name': '钱七', 'math': 88, 'english': 89, 'chinese': 85}, '001': {'name': '张三', 'math': 90, 'english': 85, 'chinese': 95}}
按语文成绩排序(降序):
{'001': {'name': '张三', 'math': 90, 'english': 85, 'chinese': 95}, '002': {'name': '李四', 'math': 85, 'english': 87, 'chinese': 88}, '003': {'name': '王五', 'math': 92, 'english': 90, 'chinese': 87}, '004': {'name': '赵六', 'math': 80, 'english': 93, 'chinese': 86}, '005': {'name': '钱七', 'math': 88, 'english': 89, 'chinese': 85}}
```