【问题标题】:Elegant way to evaluate json in recursive manner以递归方式评估 json 的优雅方法
【发布时间】:2020-03-05 22:09:01
【问题描述】:

我有一个嵌套的 json 结构,它必须根据运算符符号计算输出。我写了一个递归函数来完成任务。该解决方案对我来说看起来不太好。任何改进此功能的优雅方法将不胜感激。下面 json 的字符串表示应该产生 11。

d = ["+", 1, ["+", 3,["+", 3,4]]]

def eval_arithmetic(exp):
  op = exp[0]
  if op =="+":
     ret = exp[1] + exp[2]
  elif op == "*":
     ret = exp[1] * exp[2]
  elif op == "/":
    ret = exp[1]/exp[2]
  else:
    ret = exp[1] - exp[2]
  return ret

def eval_numberExpression(exp):
    for idx, item in enumerate(exp):
        if isinstance(item, list):
           y =  eval_numberExpression(item)
           exp[idx] = y
        if (idx == len(exp) and
            ( not isinstance(item, list))):
            val = eval_arithmetic(item)
            return val
    return eval_arithmetic(exp)

【问题讨论】:

    标签: python json recursion


    【解决方案1】:

    您可以使用递归解包:

    import operator
    d = {'+':operator.add, '*':operator.mul, '-':operator.sub, '/':operator.truediv}
    def eval_l(tokens):
       a, b, c = tokens
       return d[a](b, eval_l(c) if isinstance(c, list) else c)
    
    print(eval_l(["+", 1, ["+", 3,["+", 3,4]]]))
    

    输出:

    11
    

    【讨论】:

      猜你喜欢
      • 2015-10-29
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      • 2020-07-12
      • 2011-08-02
      相关资源
      最近更新 更多