簡體   English   中英

“列表索引超出范圍”異常(Python3)

[英]“list index out of range” exception (Python3)

當我檢查列表的長度時,我一直在獲取列表索引超出范圍的異常。 第二個if語句的ifelif部分會彈出錯誤,具體取決於用戶輸入的內容。 我知道當用戶輸入被分割時,該列表是正確創建的,因為我將其打印出來了...所以我對為什么會收到該錯誤有些困惑。

if __name__ == '__main__':
            for line in sys.stdin:
                    s = line.strip()
                    if not s: break
                    if (str(s) is "quit") == True: quit()
                    elif (str(s) is "quit") == False:
                            a = s.split()
                            print(a)
                            if (len(a) == 2) == True: first(a)
                            elif (len(a) == 3) == True: first(a)
                            else: print("Invalid Input. Please Re-enter.")

第一個方法是:(它在if語句中調用的方法此刻只是將內容打印出來)

def first(self, a = list()):
            word = a[0]

            if word is ls:
                    ls(a[1])           
            elif word is format:
                    form(a[1])        # EDIT: was format
            elif word is reconnect:
                    reconnect(a[1])
            elif word is mkfile:
                    mkfile(a[1])
            elif word is mkdir:
                    mkdir(a[1])
            elif word is append:
                    append(a[1], a[2])                               
            elif word is delfile:
                    delfile(a[1])
            elif word is deldir:
                    deldir(a[1])
            else:
                    print("Invalid Prompt. Please Re-enter.")

其他方法:

    def reconnect(one = ""):
            print("Reconnect")

    def ls(one = ""):
            print("list")

    def mkfile(one = ""):
            print("make file")

    def mkdir(one = ""):
            print("make drive")

    def append(one = "", two = ""):
            print("append")

    def form(one = ""):
            print("format")

    def delfile(one = ""):
            print("delete file")

    def deldir(one = ""):
            print("delete directory")

    def quit():
            print("quit")
            sys.exit(0)

問題似乎是first()的定義。 您可以將其作為函數調用:

if (len(a) == 2) == True: first(a)
elif (len(a) == 3) == True: first(a)

但是您將其定義為方法:

def first(self, a = list()):

命令和參數數組放入self並且a始終是一個空列表,您嘗試對其建立索引並失敗。 另外,除非您確定自己在做什么,否則不應使用像list()這樣的可變類型作為默認值。 我建議簡單:

def first(a):

就您的__main__代碼而言,請簡化:

if __name__ == '__main__':

    for line in sys.stdin:
        string = line.strip()

        if not string:
            break

        if string == "quit":
            quit()

        tokens = string.split()

        length = len(tokens)

        if 2 <= length <= 3:
            first(tokens)
        else:
            print("Invalid Input. Please Re-enter.")

實際問題:

要解決您的錯誤,您必須刪除 first函數的self參數

def first(a=list())

基本上, 自身僅用於面向對象的創建方法。 像您這樣的函數不能使用self,否則您將第一個參數傳遞給self而不是您想要的參數。

我要指出的第二個問題是,您試圖比較使用的is 字符串還是函數

 def first(a = list()):
        word = a[0]

        if word is "ls":
                ls(a[1])           
        elif word is "format":
                format(a[1])
        elif word is "reconnect":
                reconnect(a[1])
        elif word is "mkfile":
                mkfile(a[1])
        elif word is "mkdir":
                mkdir(a[1])
        elif word is "append":
                append(a[1], a[2])                               
        elif word is "delfile":
                delfile(a[1])
        elif word is "deldir":
                deldir(a[1])
        else:
                print("Invalid Prompt. Please Re-enter.")

額外

is函數基於Python的內置操作。 is比較對象的股權。

但是這個表達式:

if (str(s) is "quit") == True:

可以更簡單:

if str(s) == "quit":

要么:

if str(s) is "quit":

== True毫無意義,或者== Falsenot更多地使用Python。

暫無
暫無

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

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