Python技术咨询:如何用单条语句替代十余条if/elif处理字典武器选择
替代多条件语句的解决方案
你的需求完全可以通过字典的特性实现,不需要写十余条if/elif语句,核心是利用字典的键存在性检查来覆盖所有合法选择:
优化后的完整代码
weapons = { 1: "Dagger", 2: "Long Sword", 3: "Bastard Sword", # 在这里补充剩下9种武器的键值对(4到12) } print("\nWhat type of weapon do you use?") print("Please choose from the following:\n") for key, value in weapons.items(): print(key, ":", value) try: selection = int(input("\nSelect a number: ")) # 单条判断替代所有if/elif if selection in weapons: print(f"You have chosen the {weapons[selection]}\n") print("You have chosen, wisely.") else: print("Invalid selection! Please choose a number between 1 and 12.") except ValueError: print("Please enter a valid integer.")
关键说明
- 替代多条件判断:用
selection in weapons直接检查输入是否为字典的有效键,一次性覆盖1-12所有合法选项,省去逐条判断的冗余代码。 - 简洁的字符串拼接:使用Python的f-string(
f"...")直接嵌入字典取值,比传统的+拼接更简洁易读。 - 健壮性提升:补充了非法输入的处理逻辑——当输入非数字时捕获
ValueError,输入超出范围时提示无效选择,避免程序崩溃。
更简洁的写法(可选)
如果追求极致简洁,也可以用一行语句完成判断和输出(但可读性稍差,不推荐用于复杂场景):
print(f"You have chosen the {weapons[selection]}\nYou have chosen, wisely.") if selection in weapons else print("Invalid selection!")
内容的提问来源于stack exchange,提问作者fuzzbuzz
相关产品推荐
相关产品推荐

