Python字典操作:求最高分、最低分、平均分、第一名和不及格者
Python 字典操作:求最高分、最低分、平均分、第一名和不及格者
假设有一个字典 score_python,存储了学生的姓名和分数:
score_python = {'tom': 82, 'jerry': 85, 'ken': 90, 'petter': 72, 'robbort': 78, 'kity': 92, 'ben': 55}
1. 最高分:
max_score = max(score_python.values())
print('最高分为:', max_score)
输出结果:
最高分为: 92
2. 最低分:
min_score = min(score_python.values())
print('最低分为:', min_score)
输出结果:
最低分为: 55
3. 平均分:
sum_score = sum(score_python.values())
avg_score = sum_score / len(score_python)
print('平均分为:', avg_score)
输出结果:
平均分为: 79.0
4. 第一名:
max_name = ''
for name, score in score_python.items():
if score == max_score:
max_name = name
break
print('第一名为:', max_name)
输出结果:
第一名为: kity
5. 不及格的家伙:
fail_names = []
for name, score in score_python.items():
if score < 60:
fail_names.append(name)
if len(fail_names) == 0:
print('没有不及格的同学')
else:
print('不及格的同学为:', fail_names)
输出结果:
不及格的同学为: ['ben']
原文地址: https://www.cveoy.top/t/topic/nJec 著作权归作者所有。请勿转载和采集!