4.读取成绩文件grade.txt,自定义设计数据类型, (1)根据总评=0.7*期末+0.3*平时,计算出所有人成绩 (2)计算出不同教师的学生期末成绩平均分。
时间: 2024-10-20 16:06:06 浏览: 17
在Python中,我们可以使用内置的数据结构如字典(dict)来设计一个自定义的数据类型,例如`Student`,它包含姓名、平时成绩、期末成绩以及对应的教师信息。首先,我们假设grade.txt是一个包含学生信息的文本文件,每一行格式如下:`姓名|平时分数|期末分数|教师ID`。
```python
class Student:
def __init__(self, name, mid_term_score, final_term_score, teacher):
self.name = name
self.mid_term_score = float(mid_term_score)
self.final_term_score = float(final_term_score)
self.teacher = teacher
def read_grade_file(filename):
students = []
with open(filename, 'r') as file:
for line in file:
data = line.strip().split('|')
name, mid_term, final_term, teacher = data
students.append(Student(name, mid_term, final_term, teacher))
return students
def calculate_grades(students):
total_scores = {}
# 计算每个人的成绩
for student in students:
total = 0.7 * student.final_term_score + 0.3 * student.mid_term_score
if student.teacher not in total_scores:
total_scores[student.teacher] = [total]
else:
total_scores[student.teacher].append(total)
# 按教师统计期末平均分
teacher_averages = {teacher: sum(scores) / len(scores) for teacher, scores in total_scores.items()}
return total_scores, teacher_averages
students = read_grade_file('grade.txt')
grades, avg_terminals_by_teacher = calculate_grades(students)
# 打印结果
print("所有人的总成绩:", grades)
print("各教师的期末成绩平均分:", avg_terminals_by_teacher)
#
阅读全文