簡體   English   中英

typeerror slice索引必須為整數或不為整數,或具有__index__方法

[英]typeerror slice indices must be integers or none or have an __index__ method

我厭倦了運行該程序,但是它將在第15行給我上面的錯誤,該程序應該評估一個預算術表達式,其中需要從stdin中提取一個表達式並輸出結果

return (preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  +   preOrder( lst [ (len(lst) + 1)/2 : ] ))

這是我的程序

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))

假設:您正在運行Python 3(或有效的from __future__ import division Python 2)。 在Python 3上, /運算符是“ true”除法,並且即使對於int操作數,結果也始終是float ,這不是有效的切片索引。

如果要使用類似C的截斷除法(從技術上講是地板除法,但差與正數無關),請使用//運算符,對於int操作數,該運算符會將除法的舍入結果作為int //也可以在Python 2上使用(帶有或不__future__導入),並且可以在那里使用,以使您明確希望進行地板分割,從而簡化了向Python 3的移植。

也就是說,將(len(lst)+1)/2每個實例更改為(len(lst)+1) // 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM