typeerror slice索引必须是整数或无,或者具有__index__方法

Gol*_*eta 0 python list

我厌倦了运行这个程序,但它会在第15行给出我上面的错误程序应该评估一个预编程算术表达式,它从stdin获取一个表达式并输出结果

return (preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  +   preOrder( lst [ (len(lst) + 1)/2 : ] ))
Run Code Online (Sandbox Code Playgroud)

这是我的计划

def preOrder(lst) :
        if len(lst) == 3 :
            if lst[0] == '+' :
                return lst[1] + lst[2]
            elif lst[0] == '-' :
                return lst[1] - lst[2]
            elif lst[0] == '*' :
                return lst[1] * lst[2]
            elif lst[0] == '/' :
                return lst[1] / lst[2]
            elif lst[0] == '%' :
                return lst[1] % lst[2]
        else :
            if lst[0] == '+' :
                return (preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  +   preOrder( lst [ (len(lst) + 1)/2 : ] ))
            elif lst[0] == '-' :
                return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  -   preOrder( lst [ (len(lst) + 1)/2 : ] )
            elif lst[0] == '*' :
                return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  *   preOrder( lst [ (len(lst) + 1)/2 : ] )
            elif lst[0] == '/' :
                return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  /   preOrder( lst [ (len(lst) + 1)/2 : ] )
            elif lst[0] == '%' :
                return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  %   preOrder( lst [ (len(lst) + 1)/2 : ] )
    pre = ['+', '+', 6, 3, '-', 8, 4]
    print ("preorder:")
    print (pre)
    print (preOrder(pre))
Run Code Online (Sandbox Code Playgroud)

Sha*_*ger 8

假设:你正在运行Python 3(或者有效的Python 2 from __future__ import division).在Python 3上,/运算符是"真正的"除法,即使对于int操作数,结果也总是a float,这不是有效的切片索引.

如果你想要类似C的截断除法(技术上,地板除法,但差异与正数无关),使用//运算符,对于int操作数产生舍入的舍入结果为int.//也可以在Python 2上使用(有或没有__future__导入),可以在那里使用它来明确你想要分层,轻松移植到Python 3.

也就是说,改变的每个实例(len(lst)+1)/2(len(lst)+1) // 2.