如何在Python字典中累加条目?解决成绩计算的TypeError问题
问题:计算班级平均成绩时触发TypeError错误
问题详情
我需要编写程序从文本文件读取学生成绩(每行依次为学生ID、班级编号、字母成绩A/B/C/D/F),输出每个班级的平均分数。计划用字典映射班级与成绩来维护累计总分,再除以人数得到平均分,但无法将当前行成绩累加到对应班级条目,出现以下错误:
line 57, in
TypeError: unsupported operand type(s) for +: 'set' and 'int'
尝试的实现代码如下:
#Open the grades file for reading and create a dictionary to hold section/section grade pairs file = open("grades.txt",'r') total_section_grades = dict() #Use for loop to iterate through each line of the grades.txt file #separating the letter grade with split function for line in file: pupil_ID,section_num,alpha_grade = line.strip().split("\t") #Default numeric grade to 0 for each line in file num_grade = 0 #Conditionals to convert letter grades to numbers if alpha_grade == 'A': alpha_grade = 100 elif alpha_grade == 'B': alpha_grade = 89 elif alpha_grade == 'C': alpha_grade = 79 elif alpha_grade == 'D': alpha_grade = 74 elif alpha_grade == 'F': alpha_grade = 69 #If section number exists in total_section_grades dictionary then #update that section with num_grade variable #If section number does not exist then create new section number key and #add num_grade to dictionary if section_num in total_section_grades: total_section_grades[section_num] = total_section_grades[section_num] + num_grade else: total_section_grades[section_num] = {num_grade} #Close text file file.close() #Calculate average numerical grade for each section for current_section, grade_sum in total_section_grades.items(): average = sum(grades_sum)/len(grades_sum) print(f"{current_section} average: {average}")
错误原因及修复方案
核心问题
- 变量误用:转换后的分数被赋值给了
alpha_grade,但累加时用的是初始值为0的num_grade,等于没添加实际成绩。 - 数据类型冲突:首次创建班级条目时用了
{num_grade}(集合类型),后续试图用+将整数与集合相加,直接触发TypeError。 - 逻辑矛盾:计划维护累计总分,但代码却试图用集合存储成绩再求和,与初始设计不符。
修复后的代码
# 使用with语句自动管理文件,避免手动关闭遗漏 with open("grades.txt", 'r') as file: # 字典存储班级对应的(总分, 人数) total_section_grades = {} for line in file: line = line.strip() # 跳过空行 if not line: continue pupil_ID, section_num, alpha_grade = line.split("\t") # 字母成绩转分数 if alpha_grade == 'A': num_grade = 100 elif alpha_grade == 'B': num_grade = 89 elif alpha_grade == 'C': num_grade = 79 elif alpha_grade == 'D': num_grade = 74 elif alpha_grade == 'F': num_grade = 69 else: # 处理无效成绩,设为0并提示 num_grade = 0 print(f"警告:学生{pupil_ID}的成绩{alpha_grade}无效,按0分处理") # 更新班级的总分和人数 if section_num in total_section_grades: total_section_grades[section_num][0] += num_grade total_section_grades[section_num][1] += 1 else: # 首次添加班级时,存储[总分, 人数]列表 total_section_grades[section_num] = [num_grade, 1] # 计算并输出各班平均分,保留两位小数 for section, (total_score, student_count) in total_section_grades.items(): average = total_score / student_count print(f"{section} 平均分: {average:.2f}")
关键修复点
- 把转换后的分数赋值给
num_grade,确保累加的是实际成绩。 - 字典值改为存储
[总分, 人数]列表,既避免类型冲突,又直接维护计算平均分的核心数据。 - 用
with语句管理文件,无需手动调用close(),提升代码安全性。 - 增加空行和无效成绩处理,增强代码健壮性。
内容的提问来源于stack exchange,提问作者Churro Man
相关产品推荐
相关产品推荐

