存储学生Zhang成绩的字典结构如下: stu={"name":"Zhang","english":80,"python":90,"math":100} 1)请使用上述结构输入学生的name及english、python和math三门课的成绩并存储到字典stu中(不考虑空数据的情况); 2)计算该同学的平均成绩,同时在字典中添加关键字"avg"用来表示平均成绩; 3)由高到低排序该学生的各科成绩; 4)输出该学生的姓名,各科成绩(保留两位小数)和平均成绩(保留两位小数)。
时间: 2023-07-19 11:05:44 浏览: 229
1)输入学生的成绩并存储到字典stu中:
```python
stu = {"name": "Zhang"}
stu["english"] = 80
stu["python"] = 90
stu["math"] = 100
```
2)计算该学生的平均成绩并添加关键字"avg"到字典中:
```python
avg = (stu["english"] + stu["python"] + stu["math"]) / 3
stu["avg"] = avg
```
3)由高到低排序该学生的各科成绩:
```python
sorted_scores = sorted([(k, v) for k, v in stu.items() if k != "name" and k != "avg"], key=lambda x: x[1], reverse=True)
```
4)输出该学生的姓名和各科成绩及平均成绩:
```python
print("姓名:{0}\n英语成绩:{1:.2f}\nPython成绩:{2:.2f}\n数学成绩:{3:.2f}\n平均成绩:{4:.2f}".format(stu["name"], stu["english"], stu["python"], stu["math"], stu["avg"]))
```
完整代码如下:
```python
stu = {"name": "Zhang"}
stu["english"] = 80
stu["python"] = 90
stu["math"] = 100
avg = (stu["english"] + stu["python"] + stu["math"]) / 3
stu["avg"] = avg
sorted_scores = sorted([(k, v) for k, v in stu.items() if k != "name" and k != "avg"], key=lambda x: x[1], reverse=True)
print("姓名:{0}\n英语成绩:{1:.2f}\nPython成绩:{2:.2f}\n数学成绩:{3:.2f}\n平均成绩:{4:.2f}".format(stu["name"], stu["english"], stu["python"], stu["math"], stu["avg"]))
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)