python存储学生张三成绩的字典结构如下: d={"name":"张三","english":80,"python":90,"math":100} 请编写程序完成以下三个需求: 1)请使用上述结构,输入 5 名学生的 name 及 english、python 和 math 三门课的成绩,并 存储到列表 scores 中; 2)计算每个同学的平均成绩,同时在字典中添加关键字"avg"用来表示平均成绩; 3)按照每个学生的平均成绩由高到低排序,在控制台输出 5 个学生的相关信息,并写入 到文件 socres.txt 中。
时间: 2023-07-19 13:39:50 浏览: 164
好的,根据您的要求,我来编写 Python 代码:
```python
# 存储学生成绩的列表
scores = []
# 输入 5 名学生的成绩信息
for i in range(5):
# 输入学生姓名
name = input("请输入第%d个学生的姓名:" % (i+1))
# 输入英语成绩
english = int(input("请输入第%d个学生的英语成绩:" % (i+1)))
# 输入Python成绩
python = int(input("请输入第%d个学生的Python成绩:" % (i+1)))
# 输入数学成绩
math = int(input("请输入第%d个学生的数学成绩:" % (i+1)))
# 将成绩信息存储到字典中
d = {"name": name, "english": english, "python": python, "math": math}
# 将字典添加到列表中
scores.append(d)
# 计算每个同学的平均成绩,同时在字典中添加关键字"avg"用来表示平均成绩
for d in scores:
avg = (d["english"] + d["python"] + d["math"]) / 3
d["avg"] = avg
# 按照每个学生的平均成绩由高到低排序
scores = sorted(scores, key=lambda d: d["avg"], reverse=True)
# 在控制台输出 5 个学生的相关信息,并写入到文件 socres.txt 中
with open("scores.txt", "w") as f:
for d in scores:
print("姓名:%s,英语成绩:%d,Python成绩:%d,数学成绩:%d,平均成绩:%.2f" %
(d["name"], d["english"], d["python"], d["math"], d["avg"]))
f.write("姓名:%s,英语成绩:%d,Python成绩:%d,数学成绩:%d,平均成绩:%.2f\n" %
(d["name"], d["english"], d["python"], d["math"], d["avg"]))
```
注意:上述代码中,我们使用了 lambda 函数来指定排序规则,其中 `key=lambda d: d["avg"]` 表示按照每个学生的平均成绩进行排序,`reverse=True` 表示按照降序排列。
阅读全文
相关推荐


















