Python测验数据处理:计算平均值排障及字典实现最高分获取
解决你的Python测验数据处理需求
需求2:获取每位学生3次尝试的最高分(修正代码)
先看你当前的代码,逻辑明显偏离了“拿最高分”的目标——你现在在累加分数和尝试次数,这是算总分和总尝试数的逻辑,完全不是取最高分的思路。咱们可以简化字典的使用,只需要一个字典来跟踪每个学生的最高分就够了,没必要用三个分开的字典。
问题分析
- 冗余字典:你用了
STD_ID、ATTEMPTS、SCORE三个字典,但其实只需要一个字典存学生ID和对应的最高分 - 逻辑错误:
ATTEMPTS[did] +=3和SCORE[did] += int(ents[2])是累加操作,和“保留最高分”的需求不沾边 - 缺少异常处理:没考虑文件不存在、行格式错误、分数不是数字的情况
- 可能丢失数据:第一行
line = f.readline()会跳过一行,如果文件没有表头,就会丢失第一条学生数据
修正后的代码
# 用一个字典存储每个学生的最高分 student_highest_scores = {} try: # 用with语句自动管理文件关闭,避免资源泄漏 with open("std_attempt_score.txt", "r") as f: # 如果文件第一行是表头(比如"序号\t学生ID\t分数"),就跳过;没有表头的话注释掉这行 next(f) for line in f: line = line.strip() if not line: # 跳过空行 continue # 拆分每行数据,假设格式是:[任意字段]\t学生ID\t分数 parts = line.split("\t") # 检查拆分后的数据是否符合预期格式 if len(parts) < 3: print(f"警告:无效行格式,跳过该行:{line}") continue student_id = parts[1] try: score = int(parts[2]) except ValueError: print(f"警告:分数不是有效数字,跳过该行:{line}") continue # 更新最高分:学生不在字典里就直接存,否则比较后留大的 if student_id not in student_highest_scores: student_highest_scores[student_id] = score else: if score > student_highest_scores[student_id]: student_highest_scores[student_id] = score # 输出最终结果 print("每位学生的最高分:") for student_id, highest_score in student_highest_scores.items(): print(f"学生ID {student_id}: {highest_score}") except FileNotFoundError: print("错误:找不到文件 std_attempt_score.txt,请检查路径是否正确") except Exception as e: print(f"发生未知错误:{str(e)}")
需求1:计算测验数据的平均值并故障排查
计算平均值得先明确是所有测验分数的整体平均值还是每位学生的个人平均分,下面两种情况都给你实现,同时包含故障排查的处理逻辑。
情况1:所有测验分数的整体平均值
total_score = 0 total_attempts = 0 try: with open("std_attempt_score.txt", "r") as f: next(f) # 跳过表头(没有的话注释) for line in f: line = line.strip() if not line: continue parts = line.split("\t") if len(parts) < 3: print(f"警告:无效行,跳过:{line}") continue try: score = int(parts[2]) total_score += score total_attempts += 1 except ValueError: print(f"警告:分数不是有效数字,跳过:{line}") continue if total_attempts == 0: print("没有有效的测验分数数据") else: average = total_score / total_attempts print(f"所有测验分数的平均值:{average:.2f}") except FileNotFoundError: print("错误:文件不存在,请确认文件路径和名称") except Exception as e: print(f"意外错误:{str(e)}")
情况2:每位学生的个人平均分(基于3次尝试)
# 字典键是学生ID,值是[总分, 尝试次数] student_score_stats = {} try: with open("std_attempt_score.txt", "r") as f: next(f) for line in f: line = line.strip() if not line: continue parts = line.split("\t") if len(parts) < 3: print(f"警告:无效行,跳过:{line}") continue student_id = parts[1] try: score = int(parts[2]) if student_id not in student_score_stats: student_score_stats[student_id] = [score, 1] else: student_score_stats[student_id][0] += score student_score_stats[student_id][1] += 1 except ValueError: print(f"警告:无效分数,跳过:{line}") continue print("每位学生的平均分:") for student_id, (total, count) in student_score_stats.items(): # 尝试次数不是3的话给出提示,避免数据缺失没发现 if count != 3: print(f"学生ID {student_id}: 平均分 {total/count:.2f}(注意:仅{count}次尝试,不是3次)") else: print(f"学生ID {student_id}: 平均分 {total/count:.2f}") except FileNotFoundError: print("错误:文件不存在") except Exception as e: print(f"错误:{str(e)}")
故障排查核心要点
- 文件类问题:检查文件路径是否正确、文件是否存在、当前用户是否有读取权限
- 数据格式问题:确保每行用制表符
\t分隔,第三列是整数类型的分数 - 异常提示:代码里的警告和错误信息会帮你定位具体的错误行和问题类型
- 数据完整性:留意尝试次数不等于3的学生,这大概率是数据缺失导致的
内容的提问来源于stack exchange,提问作者Michael Marquez
相关产品推荐
相关产品推荐

