有一个班若干个学生考试的成绩表,由学号和成绩组成,将其组成一个字典如: {'1001':85,'1002':70,'1003':100,'1005':60,'1008':100}。 输出内容: 1. 按成绩从高到低输出成绩表字典; 2. 计算全班的平均分(精确到小数后两位); 3. 输出最高分的同学:学号:成绩。 输入格式: 按字典格式输入 输出格式: 输出成绩表字典、输出平均分、输出最高分。 输入样例: {'1001':85,'1002':70,'1003':100,'1005':60,'1008':100} 输出样例: {'1003': 100, '1008': 100, '1001': 85, '1002': 70, '1005': 60} 平均分=83.00 最高分: 1003:100 1008:100
时间: 2023-12-23 16:02:35 浏览: 20
可以使用 Python 的字典和内置函数,结合循环和条件语句,实现成绩表的排序、平均分计算、最高分学生的输出。
代码如下:
```python
scores = {'1001':85,'1002':70,'1003':100,'1005':60,'1008':100}
# 按成绩从高到低排序输出
sorted_scores = dict(sorted(scores.items(), key=lambda x:x[1], reverse=True))
print(sorted_scores)
# 计算平均分
avg_score = sum(scores.values()) / len(scores)
print("平均分=%.2f" % avg_score)
# 输出最高分学生的学号和成绩
max_score_students = []
max_score = max(scores.values())
for student, score in scores.items():
if score == max_score:
max_score_students.append((student, score))
print("最高分:", end="")
for student, score in max_score_students:
print(" %s:%d" % (student, score), end="")
```
代码解释:
1. 定义字典 scores 来保存学生的学号和成绩。
2. 使用 sorted 函数对成绩表字典进行排序,按成绩从高到低排序,得到一个新的有序字典 sorted_scores。
3. 使用 sum 函数和 len 函数计算平均分,并输出到控制台。
4. 使用 max 函数找到最高分。
5. 使用 for 循环遍历成绩表字典,找到最高分学生的学号和成绩,并保存到 max_score_students 列表中。
6. 使用 print 函数输出最高分学生的学号和成绩。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)