python存储学生张三成绩的字典结构如下: d= {"name。7: “张三”,"english":80, "python^ :90,”math^ :100 请编写程序完成以下三个求: 1)请使用上述结构,输入5名学生的name及english、python和math三门课的成绩,并存储到列表scores 中; 2)计算每个同学的平均成绩,同时在字典中添加关键字”avg用来表示平均成绩; 3)按照每个学生的平均成绩由 到低排序,在控制台输出5个学生的相关信息,并写入到文件socres. txt中。
时间: 2024-03-22 19:42:03 浏览: 189
代码如下:
```python
# 定义学生字典结构
student_dict = {"name": "", "english": 0, "python": 0, "math": 0, "avg": 0}
# 定义存储学生信息的列表
scores = []
# 输入5名学生的信息
for i in range(5):
# 输入学生姓名
name = input("请输入第{}个学生的姓名:".format(i+1))
student_dict["name"] = name
# 输入学生英语成绩
english_score = int(input("请输入{}的英语成绩:".format(name)))
student_dict["english"] = english_score
# 输入学生Python成绩
python_score = int(input("请输入{}的Python成绩:".format(name)))
student_dict["python"] = python_score
# 输入学生数学成绩
math_score = int(input("请输入{}的数学成绩:".format(name)))
student_dict["math"] = math_score
# 计算学生平均成绩
avg_score = (english_score + python_score + math_score) / 3
student_dict["avg"] = avg_score
# 将学生信息添加到列表中
scores.append(student_dict.copy())
# 按照平均成绩排序
scores.sort(key=lambda x: x["avg"], reverse=True)
# 输出学生信息
for i in range(5):
print("第{}名学生:".format(i+1))
print("姓名:{}".format(scores[i]["name"]))
print("英语成绩:{}".format(scores[i]["english"]))
print("Python成绩:{}".format(scores[i]["python"]))
print("数学成绩:{}".format(scores[i]["math"]))
print("平均成绩:{}".format(scores[i]["avg"]))
print()
# 将学生信息写入文件
with open("scores.txt", "w") as f:
for i in range(5):
f.write("第{}名学生:\n".format(i+1))
f.write("姓名:{}\n".format(scores[i]["name"]))
f.write("英语成绩:{}\n".format(scores[i]["english"]))
f.write("Python成绩:{}\n".format(scores[i]["python"]))
f.write("数学成绩:{}\n".format(scores[i]["math"]))
f.write("平均成绩:{}\n\n".format(scores[i]["avg"]))
```
注意:这里我们使用了`student_dict.copy()`来将每个学生的信息添加到列表中。如果我们直接将`student_dict`添加到列表中,那么所有学生的信息都将指向同一个字典,导致最终列表中的所有元素都是相同的。
阅读全文
相关推荐


















