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

如何使用Python递归计算嵌套JSON中算术表达式的结果

解决方案

错误原因

你当前的代码仅支持单层运算结构,未对嵌套的运算节点做递归处理。当plus对应的数组内的元素不是int类型节点,而是另一个运算节点时,直接提取element[k]得到的是运算数组而非整数值,因此触发int和list相加的类型错误。

实现思路

  • 编写递归函数处理每一层节点:若节点为int类型直接返回对应数值,若为运算节点则先递归计算所有子操作数的数值,再执行对应运算
  • 跳过description这类非运算字段,不影响计算逻辑
  • 兼容原有plus/minus/times三类运算的校验逻辑

完整实现代码

import json

def evaluate_node(node):
    # 处理整数节点
    if "int" in node:
        return node["int"]
    # 过滤非运算字段
    filtered_node = {k: v for k, v in node.items() if k != "description"}
    # 提取运算类型和操作数列表
    op, operands = next(iter(filtered_node.items()))
    # 递归计算所有操作数的实际值
    calc_operands = [evaluate_node(elem) for elem in operands]
    # 执行对应运算
    if op == "plus":
        return sum(calc_operands)
    elif op == "minus":
        if len(calc_operands) != 2:
            raise ValueError('minus运算需要 exactly 2个操作数')
        return abs(calc_operands[0] - calc_operands[1])
    elif op == "times":
        if len(calc_operands) != 2:
            raise ValueError('times运算需要 exactly 2个操作数')
        return calc_operands[0] * calc_operands[1]
    else:
        raise ValueError(f"不支持的运算类型: {op}")

# 调用示例
if __name__ == "__main__":
    with open("expression4.json", encoding="utf-8") as f:
        data = json.load(f)
    result = evaluate_node(data["root"])
    print(result) # 输出12,和JSON内描述的运算结果一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:54:04