代码:
student_grade_input.txt
101,刘晨曦,88 102,王雨轩,98 103,王祎伟,90 104,李威,70 105,景少帅,99 106,周泽宇,96
p013_compute_max_min_avg.py
def compute_score(): scores=[] with open("./student_grade_input.txt") as fin: for line in fin: line=line[:-1]#mov /n fields=line.split(",") scores.append(int(fields[-1])) print(scores) max_score=max(scores) min_score=min(scores) avg_score=round(sum(scores)/len(scores),2) return max_score,min_score,avg_score max_score,min_score,avg_score=compute_score() print(f"max_score={max_score},min_score={min_score},avg_score={avg_score}")
效果:
[88, 98, 90, 70, 99, 96] max_score=99,min_score=70,avg_score=90.17
总结:
- 首先读取文件用with open 路径 as fin:把文件的内容读取出来存入变量fin里面,用with命令可以保证文件内容关闭后保存;
- line=line[:-1]把行号去掉,fields=line.split(","),把每行里面加入逗号分隔,然后存入fields变量中;
- scores.append(int(fields[-1])),把最后一列加入列表中。