我被要求定义一个函数,它采用以下格式的列表:
[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
我应该怎么做才能得到正确的输出
当我运行你的代码时,我得到了一个例外:
突出显示的行显示
i
不是整数(它可能是一个列表对象),您正在尝试将其用作索引。如果需要在Pythonenumerate
函数的循环中使用的索引。然后您将能够在每次迭代中同时使用索引和当前值下面是如何使用这个有用的Python函数的示例:
如果执行此代码,您将在控制台上看到以下结果:
相关问题 更多 >
编程相关推荐