酷代码 AI
菜单
服务商

Python 实现:从 in.txt 计算学生成绩并按序写入 out.txt

解析: 1. 首先,我们需要读取文件in.txt中的内容,然后将其转换为列表的形式。 2. 然后,我们需要根据每门课的权重计算每个学生的最终成绩。 3. 接下来,我们需要将计算出的最终成绩按照从高到低的顺序进行排序。 4. 我们需要将排序后的结果写入到文件out.txt中。 代码如下: ```python def calculate_score(data): scores = [] for item in data: try: name, test1, test2, test3 = item final_score = round(test1 * 0.3 + test2 * 0.3 + test3 * 0.4, 2) scores.append((name, final_score)) except ValueError: print("输入数据错误") return scores def sort_scores(scores): return sorted(scores, key=lambda x: x[1], reverse=True) def write_to_file(scores, filename): with open(filename, 'w') as f: for item in scores: f.write(f"{item[0]} {item[1]} ") def main(): with open('in.txt', 'r') as f: lines = f.readlines() data = [line.strip().split() for line in lines[1:]] scores = calculate_score(data) sorted_scores = sort_scores(scores) write_to_file(sorted_scores, 'out.txt') if __name__ == '__main__': main() ``` 这段代码首先定义了四个函数,分别用于计算成绩、排序成绩、将成绩写入文件和主函数。在主函数中,我们首先读取文件in.txt中的内容,然后将其转换为列表的形式。接着,我们调用calculate_score函数计算每个学生的最终成绩。然后,我们调用sort_scores函数将计算出的最终成绩按照从高到低的顺序进行排序。我们调用write_to_file函数将排序后的结果写入到文件out.txt中。 ######[AI写代码神器 | 493点数解答 | 2024-06-03 21:59:31]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]