You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何消除大量if elif else语句?Python脚本优化需求

优化Python多分支elif代码结构的方案

你的代码里用了20多个elif来匹配输入选择和数组索引,这种写法不仅冗余,后期修改或新增选项也很麻烦。最直接的优化方式是用字典映射来替代所有elif分支,代码会简洁很多,维护也更方便。

优化后的完整代码

# 先定义输入选择与block索引的映射关系
choice_to_index = {
    1: 0, 2: 1, 3: 2,
    4: 6, 5: 7, 6: 8,
    7: 3, 8: 4, 9: 5,
    10: 9, 11: 10, 12: 11,
    13: 12, 14: 13, 15: 14,
    16: 15, 17: 16, 18: 17,
    19: 18, 20: 19, 21: 20,
    22: 21, 23: 22, 24: 23,
    25: 24, 26: 25
}

choice = 0
while choice == 0:
    user_input = input("Choose a block (Enter only the Number):")
    try:
        choice = int(user_input)
        # 检查输入的选择是否在映射范围内
        if choice in choice_to_index:
            print("\n", block[choice_to_index[choice]])
        else:
            print("Invalid number, please enter a number between 1 and 26.")
            choice = 0  # 重置循环
    except ValueError:
        print("That's not a number. Choose a number, numbnuts.")
        choice = 0  # 重置循环

优化点说明

  1. 用字典替代elif:把每个输入选择对应的数组索引存进字典,直接通过键值对查找,比一堆elif高效且易读,以后要调整索引对应关系,只需要修改字典就行,不用动分支代码。
  2. 更健壮的输入处理:原来的isalpha()判断有漏洞(比如输入12a或者-5会被误判),改用try-except捕获整数转换错误,能覆盖所有非有效整数的输入情况。
  3. 统一错误提示:不管是输入非数字还是超出范围的数字,都给出明确提示并重置循环,逻辑更清晰。

内容的提问来源于stack exchange,提问作者Jaxer5636

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:40:31