如果我有小明、小红和小亮三名学生的语文、数学和英语成绩数据,如何只使用Python中的字典结构和for循环来存储他们的姓名、科目和分数,并可以查询学生对应的科目分数和总分,以及谁的总分更高
时间: 2024-10-27 20:06:45 浏览: 32
你可以使用Python字典列表来存储这种信息,每个字典代表一名学生,包含姓名、三个科目的分数。这里是一个简单的例子:
```python
# 定义一个空的字典列表来存储学生信息
students = []
# 添加小明的信息
student_ming = {"name": "小明", "scores": {"语文": 90, "数学": 85, "英语": 95}}
students.append(student_ming)
# 同理添加小红和小亮的信息
student_hong = {"name": "小红", "scores": {"语文": 95, "数学": 90, "英语": 92}}
students.append(student_hong)
student_liang = {"name": "小亮", "scores": {"语文": 92, "数学": 93, "英语": 94}}
students.append(student_liang)
# 查询函数,通过名字获取成绩
def get_score(name, subject):
for student in students:
if student["name"] == name:
return student["scores"].get(subject, "未知")
return "未找到该学生"
# 计算总分
def calculate_total_score(student):
return sum(student["scores"].values())
# 比较总分
def find_student_with_highest_total():
max_total = students[0]["scores"]["语文"]
highest_student = students[0]
for student in students:
total = calculate_total_score(student)
if total > max_total:
max_total = total
highest_student = student
return highest_student
# 示例
print(f"小明的英语成绩是:{get_score('小明', '英语')}")
print(f"小红的总分是:{calculate_total_score(find_student_with_highest_total())}")
```
阅读全文