如何避免Python命令解析程序中的大量if判断语句?
如何避免命令判断中的大量if语句?
你可以通过命令-函数映射字典来替代大量的if/elif判断,这种方式让代码更简洁、扩展性更强,新增命令时只需添加对应的函数和字典条目即可。
你的原始代码
import time import os comreal = 0 com = input("Command: ") if com == "open file" or com == "openfile": comreal = comreal + 1 file = input("File Name: ") os.system(file) if com == "delete file" or com == "deletefile": comreal = comreal + 1 filefordelete = input("File name: ") if os.path.exists(filefordelete): suretodelete = input("Are you sure? Y/N ") if suretodelete == "Y" or suretodelete == "y": os.remove(filefordelete) print("Deleting successful") elif suretodelete == "N" or suretodelete == "n": print("Deleting stopped!") else: print("File does not exist!") if com == "create file" or com == "createfile": comreal = comreal + 1 filename = input("Name of the file you want to create: ") filename2 = str(filename) + ".txt" textinput = input("Text: ") with open(filename2, "w") as a: a.write(textinput) if comreal == 0: print("This command does not exist") input("Press enter to exit ")
优化后的代码
import os def handle_open_file(): file = input("File Name: ") os.system(file) def handle_delete_file(): filefordelete = input("File name: ") if os.path.exists(filefordelete): suretodelete = input("Are you sure? Y/N ").lower() if suretodelete == "y": os.remove(filefordelete) print("Deleting successful") elif suretodelete == "n": print("Deleting stopped!") else: print("File does not exist!") def handle_create_file(): filename = input("Name of the file you want to create: ") filename2 = f"{filename}.txt" textinput = input("Text: ") with open(filename2, "w") as a: a.write(textinput) # 命令映射字典:键为所有可识别的命令,值为对应的处理函数 command_map = { "open file": handle_open_file, "openfile": handle_open_file, "delete file": handle_delete_file, "deletefile": handle_delete_file, "create file": handle_create_file, "createfile": handle_create_file } com = input("Command: ") # 从字典中获取处理函数,不存在则返回None handler = command_map.get(com) if handler: handler() else: print("This command does not exist") input("Press enter to exit ")
优化思路说明
- 封装处理逻辑:把每个命令的执行代码封装成独立函数,职责清晰,便于维护和修改。
- 命令映射字典:用字典将所有可识别的命令字符串与对应的处理函数绑定,输入命令后直接通过字典查找函数并执行,彻底替代if/elif判断。
- 简化冗余代码:比如将大小写判断改为
.lower(),用f-string简化字符串拼接,去掉了冗余的comreal变量(通过字典查找结果直接判断命令是否有效)。
这种方式的优势在于,后续新增命令时,只需要:
- 编写对应的处理函数
- 在
command_map中添加新的命令-函数映射
完全不需要修改判断逻辑部分,扩展性极强。
内容的提问来源于stack exchange,提问作者7Nilklaz
相关产品推荐
相关产品推荐

