目录
一、题目
文本文件中保存了学生多次测试的成绩。每个学生每次测试成绩占一行,某行数据如:0001 小明 95 请统计每个学生的平均分。
二、数据样例
三、实验代码
import csv rows3 = ['Num', 'Name', 'Avg_grade'] f = open("../source/result.csv", 'a', newline='', encoding='utf-8') writer = csv.writer(f) writer.writerow(rows3) f.close() f = open("../source/stu_score.txt",'r', encoding='gbk') score = [] num = [] name = [] score_m = 0 count = 0 for line in f: score.append(line.split()[2].strip()) num.append(line.split()[0].strip()) name.append(line.split()[1].strip()) f.close() num_del = list(set(num)) for i in num_del: for j in num: if i==j: index = [p for p,v in enumerate(num) if v ==j] h_name = name[num.index(j)] break count = len(index) for m in index: score_m = score_m + int(score[m]) avg = score_m/count print("学号为:",i,"的学生",h_name,"平均成绩为:",avg) rows3 = [i, h_name, avg] f = open("../source/result.csv", 'a', newline='',encoding='utf-8') writer = csv.writer(f) writer.writerow(rows3) f.close() count = 0 score_m = 0 avg = 0
(本代码为参考解答,非最优解,可精简)
四、实验结果
写入csv:
打开查看: