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

如何减少Python代码中的if语句数量?以Minecraft资源计算器开发为例

解决方案

你可以通过字典映射的方式完全消除掉冗余的if判断,这里提供两种可落地的实现方案:


方案1:函数字典映射

如果不同物品的计算逻辑差异很大,无法复用,可以直接把物品名和对应的处理函数绑定为字典的键值对,运行时直接查表调用即可:

def hoppercalc(noofitems):
    # 建议把数量作为参数传入,不要用全局变量,代码可维护性更高
    print(f"{noofitems * 5} iron")

def pistoncalc(noofitems):
    print(f"{noofitems * 3} planks, {noofitems * 4} cobblestone, {noofitems} redstone and iron")

# 建立物品名到计算函数的映射
calc_func_map = {
    "hopper": hoppercalc,
    "piston": pistoncalc
}

noofitems = int(input("How many items do you want to make? "))
itemname = input("What item do you want to make? ")

# 直接查表调用,不用写if
if itemname in calc_func_map:
    calc_func_map[itemname](noofitems)
else:
    print("暂不支持该物品的计算")

方案2:配方数据通用计算(更推荐)

对于资源计算器这类场景,绝大多数物品的计算逻辑都是「单份素材需求 × 制作数量」,完全可以把所有配方都存在统一的数据结构里,用一套通用逻辑处理,后续加新物品不需要新增函数、不需要改业务逻辑,只要加一行配方配置即可:

# 所有配方统一存在这里,键是物品名,值是单份物品的素材需求字典
recipe_map = {
    "hopper": {
        "iron": 5
    },
    "piston": {
        "planks": 3,
        "cobblestone": 4,
        "redstone": 1,
        "iron": 1
    }
}

def calc_resource(item_name, count):
    if item_name not in recipe_map:
        print("暂不支持该物品的计算")
        return
    recipe = recipe_map[item_name]
    # 按数量计算所有素材
    resource_list = [f"{count * num} {name}" for name, num in recipe.items()]
    # 格式化输出
    if len(resource_list) == 1:
        print(resource_list[0])
    else:
        print(f"{', '.join(resource_list[:-1])} and {resource_list[-1]}")

noofitems = int(input("How many items do you want to make? "))
itemname = input("What item do you want to make? ")
calc_resource(itemname, noofitems)

两种方案都完全消除了原有代码里的if分支判断,其中方案2的扩展性更强,后续要新增支持的物品,只要在recipe_map里加对应的配方条目即可,不需要修改任何逻辑代码,非常适合需要支持大量物品种类的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:00:01