面试题答案
一键面试# 定义成绩分类的区间
score_ranges = {
'A': (270, 300),
'B': (240, 269),
'C': (210, 239),
'D': (180, 209),
'E': (0, 179)
}
def classify_students(input_file):
student_dict = {category: [] for category in score_ranges.keys()}
with open(input_file, 'r', encoding='utf-8') as f:
for line in f:
student_name, chinese_score, math_score, english_score = line.strip().split(',')
total_score = int(chinese_score) + int(math_score) + int(english_score)
for category, (lower, upper) in score_ranges.items():
if lower <= total_score <= upper:
student_dict[category].append(line)
break
for category, students in student_dict.items():
output_file = f'{category}_students.txt'
with open(output_file, 'w', encoding='utf-8') as f:
f.writelines(students)
if __name__ == "__main__":
input_file = 'students_scores.txt'
classify_students(input_file)
上述代码实现了以下功能:
- 定义成绩分类区间:通过字典
score_ranges
定义了不同成绩区间对应的类别。 - 读取文件并分类学生:从输入文件中逐行读取学生成绩记录,计算总分后,将学生记录归类到对应的类别列表中。
- 写入新文件:将每个类别中的学生记录写入到对应的新文件中,新文件命名规则为
类别名_students.txt
。这样处理在文件读写效率上,采用逐行读取和写入的方式,减少内存占用,同时通过一次遍历完成分类,保证了数据的准确性。