Python循环仅输出1次而非多次:专业代码匹配功能实现问题
问题解决方法
原有代码的核心问题是在遍历每个别名的循环内直接执行输出,不管匹配是否成功都会触发打印操作,自然会生成大量重复结果,同时逻辑判断中major == values的条件完全无效(输入是字符串,values是列表,不可能相等)。
修改思路
- 遍历字典的键值对,直接判断输入的
major是否存在于对应别名列表中,省略不必要的内层循环 - 匹配到结果后直接返回对应专业编码,终止后续遍历,避免重复输出
- 只有遍历完全部字典条目都未匹配到结果时,再返回大写的输入参数
- 把输出逻辑移到循环外部,杜绝重复打印的问题
修正后的代码
student_majors_vari = { 'COMP':['compsci','comp sci','computer sci','computer science'], 'CMPE':['compeng', 'comp eng', 'computer eng', 'computer engineering'], 'EE':['eleceng', 'elec eng', 'elec engineering', 'electrical engineering'], 'MATH':['mathsci', 'math sci', 'mathematical sci', 'mathmatical sciences', 'mathematics'] } def get_major_code(major): for major_code, alias_list in student_majors_vari.items(): if major in alias_list: # 匹配到直接返回对应编码,终止遍历 return major_code # 全量遍历无匹配,返回大写输入 return major.upper()
测试验证
执行如下测试代码:
print(get_major_code('education')) print(get_major_code('comp sci'))
输出结果符合预期:
EDUCATION COMP
内容的提问来源于stack exchange,提问作者Beyn18
相关产品推荐
相关产品推荐

