如何用Python的add_course函数替换列表中低成绩课程元组
修正后的代码
def add_student(students, name): if name not in students: students[name] = [] def print_student(students, name): if name not in students: print(f"{name}: no such person in the database") elif len(students[name]) < 1: print(f"{name}:") print(" no completed courses") else: print(f"{name}:") print(f" {len(students[name])} completed courses:") for course in students[name]: print(f" {course[0]} {course[1]}") av_grade = sum(course[1] for course in students[name]) / len(students[name]) print(f" average grade {av_grade}") def add_course(students, name, course: tuple): course_name, new_score = course # 成绩为0时直接返回,不添加课程 if new_score == 0: return # 遍历已修课程,查找同名课程 for idx, (existing_course, existing_score) in enumerate(students[name]): if existing_course == course_name: # 新成绩更高则替换原有课程记录 if new_score > existing_score: students[name][idx] = course # 无论是否替换,都终止函数,避免重复添加 return # 未找到同名课程,添加新课程 students[name].append(course) if __name__ == "__main__": students = {} add_student(students, "Peter") add_course(students, "Peter", ("Introduction to Programming", 3)) add_course(students, "Peter", ("Advanced Course in Programming", 2)) add_course(students, "Peter", ("Data Structures and Algorithms", 0)) add_course(students, "Peter", ("Introduction to Programming", 2)) print_student(students, "Peter")
关键修改说明
- 修复课程存在性判断逻辑:原代码用
course[0] in students[name]判断课程是否存在,这是错误的——students[name]存储的是课程元组,而course[0]是字符串,永远无法匹配。现在改为遍历列表中的元组,检查元组的第一个元素(课程名)是否匹配。 - 实现成绩替换逻辑:找到同名课程后,对比新旧成绩,只有新成绩更高时,才用新的课程元组替换原有记录;若新成绩更低或相等,直接返回不做操作。
- 简化平均成绩计算:原代码用两次循环计算平均分,改为用生成器表达式结合
sum()函数,更简洁高效。 - 优化print_student分支:将
elif len(students[name]) > 0改为else,逻辑更简洁,因为前面已经判断过学生存在且课程列表为空的情况。
运行修正后的代码,输出将符合预期:
Peter: 2 completed courses: Introduction to Programming 3 Advanced Course in Programming 2 average grade 2.5
内容的提问来源于stack exchange,提问作者John Fox
相关产品推荐
相关产品推荐

