优化并完善以下程序with open('rawscore.txt', 'r') as f: lines = f.readlines() students = []for line in lines: parts = line.strip().split() # 分割字符串 student = { 'id': parts[0], 'name': parts[1], 'scores': [int(x) for x in parts[2:]] # 将成绩转换为整数 } students.append(student) for student in students: scores = student['scores'][:3] # 取前3门课程的成绩 avg_score = sum(scores) / len(scores) # 计算平均分 student['avg_score'] = avg_score # 设置参数weight_major = 0.7 # 专业课成绩所占比例 weight_moral = 0.3 # 德育成绩所占比例 num_grades = 5 # 奖学金等级数 num_winners = [10, 20, 30, 40, 50] # 各等级获奖人数 # 根据综合成绩排序 for i in range(len(students)): for j in range(len(students) - i - 1): if students[j]['avg_score'] < students[j+1]['avg_score']: students[j], students[j+1] = students[j+1], students[j]# 输出获奖名单 for i in range(num_grades): print(f'第{i+1}等奖:') for j in range(num_winners[i]): student = students[j] score_major = student['avg_score'] * weight_major score_moral = student['scores'][3] * weight_moral score_total = score_major + score_moral if j == 0: print(f' {j+1}. {student["name"]}({student["id"]}),综合成绩:{score_total:.2f},专业课平均分:{student["avg_score"]:.2f},德育成绩:{student["scores"][3]:.2f},获得一等奖学金') elif j < num_winners[i-1]: print(f' {j+1}. {student["name"]}({student["id"]}),综合成绩:{score_total:.2f},专业课平均分:{student["avg_score"]:.2f},德育成绩:{student["scores"][3]:.2f},获得其他奖学金') else: break
时间: 2024-03-27 20:36:23 浏览: 66
可以优化的部分有:
1. 使用 with 语句可以避免手动关闭文件。
2. 可以使用列表推导式来简化代码。
3. 在排序时可以使用 sorted() 函数来代替手动排序。
下面是优化后的代码:
```python
# 读取文件并转换为字典列表
with open('rawscore.txt', 'r') as f:
lines = f.readlines()
students = [
{
'id': parts[0],
'name': parts[1],
'scores': [int(x) for x in parts[2:]]
}
for line in lines
for parts in [line.strip().split()]
]
# 计算平均分并排序
for student in students:
scores = student['scores'][:3]
avg_score = sum(scores) / len(scores)
student['avg_score'] = avg_score
students = sorted(students, key=lambda x: x['avg_score'], reverse=True)
# 输出获奖名单
weight_major = 0.7
weight_moral = 0.3
num_grades = 5
num_winners = [10, 20, 30, 40, 50]
for i in range(num_grades):
print(f'第{i+1}等奖:')
for j in range(num_winners[i]):
student = students[j]
score_major = student['avg_score'] * weight_major
score_moral = student['scores'][3] * weight_moral
score_total = score_major + score_moral
if j == 0:
print(f' {j+1}. {student["name"]}({student["id"]}),综合成绩:{score_total:.2f},专业课平均分:{student["avg_score"]:.2f},德育成绩:{student["scores"][3]:.2f},获得一等奖学金')
elif j < num_winners[i-1]:
print(f' {j+1}. {student["name"]}({student["id"]}),综合成绩:{score_total:.2f},专业课平均分:{student["avg_score"]:.2f},德育成绩:{student["scores"][3]:.2f},获得其他奖学金')
else:
break
```
阅读全文