处理成绩文件计算平均分遇TypeError: string indices must be integers如何修复?
问题解决:读取成绩文件计算班级平均分的TypeError修复
问题背景
我正在完成一项作业,编写程序读取Grades.txt文件中的成绩数据,计算每个班级的平均分,但遇到了TypeError: string indices must be integers错误,错误出现在代码行sections[sec]["total"] = grade[grade]。以下是我的原始代码:
grades = {'A': 100, 'B': 89, 'C': 79, 'D': 74, 'F': 69} # 读取文件部分 def calculate_average(): file = open("grades.txt", "r") sections = {} for line in file: [_, sec, grade] = line.split("\t") grade = grade.strip() if sec in sections: sections[sec]["count"] += 1 sections[sec]["total"] += grade[grade] else: sections[sec] = {} sections[sec]["count"] = 1 sections[sec]["total"] = grade[grade] file.close() # 计算平均分部分 for sec, secdata in sections.items(): avg = secdata[" total "] / secdata[" count"] print(" {0} : {1}".format(sec, round(avg, 2))) if __name__ == "__main__": calculate_average()
错误原因分析
- 核心错误:
grade[grade]是完全错误的用法。grade是从文件读取的字符串类型成绩(如"A"、"B"),字符串的索引必须是整数,用字符串作为索引访问自身必然触发TypeError。正确做法是用这个字母成绩查询预先定义的grades字典,获取对应分数值,即grades[grade]。 - 次要问题:计算平均分的代码中,字典键
" total "和" count"带有多余空格,会导致KeyError,因为存储数据时用的键是"total"和"count"。 - 文件处理隐患:直接用
open()后手动close(),若程序中途报错,文件可能无法正常关闭,推荐用with语句自动管理文件生命周期。
修正后的代码
grades = {'A': 100, 'B': 89, 'C': 79, 'D': 74, 'F': 69} def calculate_average(): # 使用with语句自动处理文件关闭,更安全 with open("grades.txt", "r") as file: sections = {} for line in file: # 去除行首尾空白,跳过空行 line = line.strip() if not line: continue parts = line.split("\t") # 校验行数据格式,避免索引越界 if len(parts) < 3: continue _, sec, grade = parts[:3] grade = grade.strip() # 获取对应分数,用get方法兼容未定义的成绩等级 score = grades.get(grade, 0) if sec in sections: sections[sec]["count"] += 1 sections[sec]["total"] += score else: # 简化字典初始化 sections[sec] = {"count": 1, "total": score} # 计算并打印每个班级的平均分 for sec, secdata in sections.items(): avg = secdata["total"] / secdata["count"] # 使用f-string简化格式化 print(f"{sec} : {round(avg, 2)}") if __name__ == "__main__": calculate_average()
关键修正点
- 将
grade[grade]替换为grades.get(grade, 0),实现字母成绩到分数值的映射,同时兼容未定义的成绩等级; - 修正平均分计算时的字典键,去掉多余空格;
- 改用
with语句处理文件,避免资源泄漏; - 增加行格式校验,跳过空行和格式错误的行,提升程序健壮性;
- 用f-string替代
format(),简化字符串格式化。
内容的提问来源于stack exchange,提问作者Sadaya Preston
相关产品推荐
相关产品推荐

