Python读取Diving.csv计算跳水选手最终得分问题排查
问题排查与修复方案
1. 文件读取函数(ReadFile)的核心问题
- 类变量误用:你定义的
Diving类里,score1到score11是类变量,所有实例会共享这些值,导致后面选手的得分会覆盖前面的。必须改成实例变量,在__init__方法里初始化。 - 固定长度列表风险:预先创建10个
Diving实例,如果CSV文件里的选手数量不是10,要么会出现索引越界(超过10行时),要么会保留空实例(不足10行时),应该动态添加实例。
2. 得分计算函数(CalcScores)的冗余与优化点
- 手动遍历找高低分没必要:Python内置
min()和max()函数可以直接获取列表的最小/最大值,比手动循环更高效且不易出错。 - 手动求和太繁琐:用
sum()函数直接计算分数列表的总和,避免重复写11个变量相加。 - 缺少高低分展示:原程序没按需求输出每位选手的最高分和最低分,需要补充这部分逻辑。
修复后的完整代码
# 读取文件函数 def ReadFile(): class Diving(): def __init__(self): self.score1 = 0.0 self.score2 = 0.0 self.score3 = 0.0 self.score4 = 0.0 self.score5 = 0.0 self.score6 = 0.0 self.score7 = 0.0 self.score8 = 0.0 self.score9 = 0.0 self.score10 = 0.0 self.score11 = 0.0 diving = [] counter = 0 with open("Diving.csv", "r") as readfile: line = readfile.readline().rstrip("\n") while line: items = line.split(",") # 动态创建选手实例 diver = Diving() diver.score1 = float(items[0]) diver.score2 = float(items[1]) diver.score3 = float(items[2]) diver.score4 = float(items[3]) diver.score5 = float(items[4]) diver.score6 = float(items[5]) diver.score7 = float(items[6]) diver.score8 = float(items[7]) diver.score9 = float(items[8]) diver.score10 = float(items[9]) diver.score11 = float(items[10]) diving.append(diver) line = readfile.readline().rstrip("\n") counter += 1 input("文件读取完成... 按任意键继续") return diving # 计算得分函数 def CalcScores(diving): scores = [] for idx, diver in enumerate(diving): # 整理当前选手的所有分数到列表 diver_scores = [ diver.score1, diver.score2, diver.score3, diver.score4, diver.score5, diver.score6, diver.score7, diver.score8, diver.score9, diver.score10, diver.score11 ] min_val = min(diver_scores) max_val = max(diver_scores) # 展示当前选手的高低分 print(f"选手{idx+1} - 最高分: {max_val}, 最低分: {min_val}") # 计算最终得分 total = sum(diver_scores) - min_val - max_val final_score = total * 0.6 scores.append(final_score) return scores # 展示得分函数 def DisplayScore(scores): for counter, score in enumerate(scores, 1): print(f"选手{counter}最终得分 = {round(score, 2)}") # 主程序 diving_data = ReadFile() final_scores = CalcScores(diving_data) DisplayScore(final_scores)
额外优化建议
- 可以把
Diving类的11个score变量换成一个列表,比如self.scores = [],读取时直接写diver.scores = [float(item) for item in items],后续处理会更灵活。 - 处理CSV文件时建议用Python内置的
csv模块,比手动split(",")更健壮,能处理带引号的字段等特殊情况。
内容的提问来源于stack exchange,提问作者Hexana
相关产品推荐
相关产品推荐

