Python 计算括号内的表达式

Python 计算括号内的表达式,python,list,Python,List,我被要求定义一个采用以下格式列表的函数: [2,“+”,5],3,5] 并返回一个带有计算表达式的列表,例如 [7,3,5] 这是我的代码: 这就是我得到的错误: evalExpr(lst)中的 5 """ 6对于lst中的i: ---->7如果len(lst[i])==3: 8对于lst中的j[i]: 9如果lst[i][j]==“+”: TypeError:列表索引必须是整数或片,而不是列表 为了获得正确的输出,我应该怎么做?当我运行您的代码时,我得到的是一个例外: ---

我被要求定义一个采用以下格式列表的函数:

  • [2,“+”,5],3,5]
并返回一个带有计算表达式的列表,例如

  • [7,3,5]
这是我的代码: 这就是我得到的错误: evalExpr(lst)中的

5     """
6对于lst中的i:
---->7如果len(lst[i])==3:
8对于lst中的j[i]:
9如果lst[i][j]==“+”:
TypeError:列表索引必须是整数或片,而不是列表

为了获得正确的输出,我应该怎么做?

当我运行您的代码时,我得到的是一个例外:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-1d51996f7143> in <module>
----> 1 evalExpr([[2, "+", 5], 3, 5])

<ipython-input-1-5c5345233e02> in evalExpr(lst)
      5     """
      6     for i in lst:
----> 7         if len(lst[i]) == 3:
      8             for j in lst[i]:
      9                 if lst[i][j]== "+":

TypeError: list indices must be integers or slices, not list
如果执行此代码,您将在控制台上看到此结果:

[7, 3, 5, 8, 16]

什么不起作用?输出不好?错误?具体点,如果有的话,发布堆栈转储。提示:仔细查看for循环并阅读其文档。提示2:在代码中,
i
不是索引(也不是
j
)。这可能会让您感兴趣:最外层的if语句应该有一个else-clausethanks作为详细的解释,我只想知道这部分检查
if-str(type(e))。find('list')>-1
?@MisterTusk这只是检查当前元素的类型是否
type(e)
是一个列表。事实上,这相当笨拙;因此,我使用now
isinstance(e,list)
更新了答案,它做了同样的事情,而且更加优雅。
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-1d51996f7143> in <module>
----> 1 evalExpr([[2, "+", 5], 3, 5])

<ipython-input-1-5c5345233e02> in evalExpr(lst)
      5     """
      6     for i in lst:
----> 7         if len(lst[i]) == 3:
      8             for j in lst[i]:
      9                 if lst[i][j]== "+":

TypeError: list indices must be integers or slices, not list
def evalExpr(lst):
    """
    parameters : lst of type lst:
    returns : evaluation of the expression inside brackets;
    """
    for i, e in enumerate(lst): # i is the index and e the actual element in the iteration
        if isinstance(e, list) and len(e) == 3:
            lst[i] = eval(str(lst[i][0]) + lst[i][1] + str(lst[i][2]))
    return lst

new_list = evalExpr([[2, "+", 5], 3, 5, [2,'*', 4], [2,'**', 4]])

print(new_list)
[7, 3, 5, 8, 16]