Python字典实战:学生信息管理与分析
Python字典实战:学生信息管理与分析
本文将带你学习如何使用Python字典存储和管理学生信息,并进行一些基本的数据分析。
1. 创建学生信息字典
我们需要创建一个名为student_info的字典,用于存储10名学生的信息。字典的键为学号,值为另一个字典,包含学生的姓名、性别、课程名(Python)和成绩。pythonstudent_info = { '2010': {'姓名': '张三', '性别': '男', '课程名': 'Python', '成绩': 80}, '2011': {'姓名': '李四', '性别': '男', '课程名': 'Python', '成绩': 75}, '2012': {'姓名': '王五', '性别': '女', '课程名': 'Python', '成绩': 85}, # ... 添加更多学生信息 ...}
2. 计算平均成绩
接下来,我们将分别计算所有学生的平均成绩、男生的平均成绩和女生的平均成绩。pythontotal_score = 0male_count = 0male_score = 0female_count = 0female_score = 0
for student in student_info.values(): total_score += student['成绩']
if student['性别'] == '男': male_count += 1 male_score += student['成绩'] elif student['性别'] == '女': female_count += 1 female_score += student['成绩']
average_score = total_score / len(student_info)average_male_score = male_score / male_count if male_count > 0 else 0average_female_score = female_score / female_count if female_count > 0 else 0
print('所有学生的平均成绩:', average_score)print('男生的平均成绩:', average_male_score)print('女生的平均成绩:', average_female_score)
3. 修改成绩低于60分的学生信息
最后,我们将所有成绩低于60分的学生成绩修改为60分,并输出修改前后学生的所有信息。python# 修改成绩低于60分的学生信息为60分for student in student_info.values(): if student['成绩'] < 60: student['成绩'] = 60
输出成绩修改前后学生的所有信息for student_id, student in student_info.items(): print('学号:', student_id) print('姓名:', student['姓名']) print('性别:', student['性别']) print('课程名:', student['课程名']) print('成绩:', student['成绩']) print()
总结
本文介绍了如何使用Python字典存储和管理学生信息,并进行了一些基本的数据分析操作。你可以根据自己的需求扩展代码,例如添加新的学生信息、计算其他科目的成绩等等。
原文地址: https://www.cveoy.top/t/topic/zc5 著作权归作者所有。请勿转载和采集!