如何消除代码中匹配后的重复学生记录?循环逻辑问题排查
问题描述
匹配到“1st name”后按逻辑应退出循环,但输出中仍出现“Student Created inside Else 1st name”这类记录,请求消除该错误记录。
可运行代码
student_for_admission = [{"student_name": "1st name", "other_key": "other_val"},{"student_name": "johndoe", "student":"other_val"}] Student_eligible = [{"name": "1st name", "other_key": "other_val1", "another_key": "another_val2"},{"name": "2nd name", "other_key": "other_val", "another_key": "another_val"},{"name": "3rd name", "other_key": "other_val", "another_key": "another_val"}] student_created=0 student_updated=0 student_skipped=0 for student in student_for_admission: for eligible in Student_eligible: if eligible["name"] == student["student_name"]: # Matching student found print("Student updated " + eligible["name"]) print("Skipped " + eligible["name"]) student_skipped += 1 print(student_skipped) print("Before break") break print("After break") else: # Create Student print("Student Created inside Else "+ eligible["name"]) student_created += 1
当前输出
Student updated 1st name Skipped 1st name 1 Before break Student Created inside Else 1st name Student Created inside Else 2nd name Student Created inside Else 3rd name
问题原因
代码逻辑存在错误:内层循环中每一次eligible与当前student不匹配时,都会执行else里的创建操作,而非遍历完所有eligible都未找到匹配才执行创建。
- 第一个学生“1st name”匹配到第一个eligible后退出内层循环,这部分逻辑正常;
- 第二个学生“johndoe”遍历所有3个eligible都未匹配,因此每一次不匹配都会触发else分支,导致输出三条创建记录,其中就包含“1st name”的那条。
解决方案
添加标记变量记录是否找到匹配学生,仅当遍历完所有eligible都未找到匹配时,才执行创建操作:
student_for_admission = [{"student_name": "1st name", "other_key": "other_val"},{"student_name": "johndoe", "student":"other_val"}] Student_eligible = [{"name": "1st name", "other_key": "other_val1", "another_key": "another_val2"},{"name": "2nd name", "other_key": "other_val", "another_key": "another_val"},{"name": "3rd name", "other_key": "other_val", "another_key": "another_val"}] student_created=0 student_updated=0 student_skipped=0 for student in student_for_admission: found = False # 标记是否找到匹配学生 for eligible in Student_eligible: if eligible["name"] == student["student_name"]: # 找到匹配学生 print("Student updated " + eligible["name"]) print("Skipped " + eligible["name"]) student_skipped += 1 print(student_skipped) print("Before break") found = True break # 遍历完所有eligible都未找到匹配,才创建学生 if not found: print("Student Created " + student["student_name"]) student_created += 1
修改后输出
Student updated 1st name Skipped 1st name 1 Before break Student Created johndoe
内容的提问来源于stack exchange,提问作者An_pack
相关产品推荐
相关产品推荐

