$ with open("score1.txt", 'w') as file: file.write("学号,平时成绩,期末成绩,总评成绩 \n") file.write("2022001,86,97 \n") file.write("2022002,93,85\n") file.write("2022003,78,90 \n") file.write("2022004,79,86 \n") file.write("2022005,84,89\n") file.write("2022006,90,75\n") scores = [] with open("score1.txt", 'r') as file: lines = file.readlines() for line in lines[1:]: data = line.strip().split(',') id = data[0] regular = fl(data[1]) final = int(data[2]) total = round(regular * 0.4 + final * 0.6) scores.append((id, regular, final, total)) scores.sort(key=lambda x: x[3], reverse=True) with open("score1.txt", 'w') as file: file.write("学号,平时成绩,期末成绩,总评成绩\n") for score in scores: file.write(f"{score[0]},{score[1]},{score[2]},{score[3]}\n")
$ with open("score.csv", 'w') as file: file.write("学号,英语,数学,计算机程序设计 \n") file.write("20210101,78,90,88 \n") file.write("20210102,89,77,65\n") file.write("20210103,76,87,90 \n") file.write("20210104,78,80,86 \n") file.write("20210105,87,90,89\n") file.write("20210106,76,89,85\n") scores = [] with open("score.csv", 'r') as file: lines = file.readlines() header = lines[0].strip().split(',') for line in lines[1:]: data = line.strip().split(',') user = data[0] subject = [int(i) for i in data[1:]] total = sum(subject) scores.append([user] + data[1:] + [str(total)]) num_subjects = len(header) - 1 avg_scores = ["平均分"] for i in range(num_subjects): subject = [int(score[i + 1]) for score in scores] avg_score = sum(subject) / len(subject) avg_scores.append(str(round(avg_score, 2))) header.append("总分") with open("score1.csv", 'w') as file: file.write(','.join(header) + '\n') for i in scores: file.write(','.join(i) + '\n') file.write(','.join(avg_scores))