Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 以递归方式计算json的优雅方法_Python_Json_Recursion - Fatal编程技术网

Python 以递归方式计算json的优雅方法

Python 以递归方式计算json的优雅方法,python,json,recursion,Python,Json,Recursion,我有一个嵌套的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[

我有一个嵌套的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)

您可以使用递归解包:

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

您可以使用递归解包:

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