计算括号内的表达式

2024-09-30 14:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

  • [2, "+", 5], 3, 5]

并返回一个带有计算表达式的列表,例如

  • [7, 3, 5]

这是我的代码:

def evalExpr(lst):
    """
    parameters : lst of type lst:
    returns : evaluation of the expression inside brackets;
    """
    for i in lst:
        if len(lst[i]) == 3:
            for j in lst[i]:
                if lst[i][j]== "+":
                    lst[i] = lst[i][j-1] + lst[i][j+1]
    return lst

print(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

我应该怎么做才能得到正确的输出


Tags: of函数代码in列表forlenif
1条回答
网友
1楼 · 发布于 2024-09-30 14:20:48

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

                                     -
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

突出显示的行显示i不是整数(它可能是一个列表对象),您正在尝试将其用作索引。如果需要在Pythonenumerate函数的循环中使用的索引。然后您将能够在每次迭代中同时使用索引和当前值

下面是如何使用这个有用的Python函数的示例:

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]

相关问题 更多 >