简体   繁体   English

“列表索引超出范围”异常(Python3)

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

I keep getting a list index out of range exception when I check the length of the list a. 当我检查列表的长度时,我一直在获取列表索引超出范围的异常。 The error pops up for either the if or elif part of the second if statement, depending on what the user inputs. 第二个if语句的ifelif部分会弹出错误,具体取决于用户输入的内容。 I know that when the user input is split the list is created correctly because I print it out... So I'm a little lost about why I'm getting that error. 我知道当用户输入被分割时,该列表是正确创建的,因为我将其打印出来了...所以我对为什么会收到该错误有些困惑。

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

The first method is: (The methods it calls in the if statement just print things out at the moment) 第一个方法是:(它在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.")

Other methods: 其他方法:

    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)

The problem seems to be the definition of first() . 问题似乎是first()的定义。 You invoke it as a function: 您可以将其作为函数调用:

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

But you define it as a method: 但是您将其定义为方法:

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

The array of command and argument gets put into self and a is always an empty list which you attempt to index and fail. 命令和参数数组放入self并且a始终是一个空列表,您尝试对其建立索引并失败。 Also, you shouldn't use a mutable type like list() as a default value unless you're certain what you are doing. 另外,除非您确定自己在做什么,否则不应使用像list()这样的可变类型作为默认值。 I suggest simply: 我建议简单:

def first(a):

As far as your __main__ code goes, simplify: 就您的__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.")

Real issue: 实际问题:

To solve your error you have to remove the self parameter of the first function 要解决您的错误,您必须删除 first函数的self参数

def first(a=list())

Basically the self is only used for object orientation creating methods. 基本上, 自身仅用于面向对象的创建方法。 Function like yours can't use self otherwise you will passing the first parameter to self not to a which you want to. 像您这样的函数不能使用self,否则您将第一个参数传递给self而不是您想要的参数。

My second issue I can point out is that, You are trying to compare using is between a string and a function . 我要指出的第二个问题是,您试图比较使用的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.")

Extra 额外

The is function on built in operations in Python. is函数基于Python的内置操作。 is compare the equity of the objects. is比较对象的股权。

But this expression: 但是这个表达式:

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

Can be simpler like: 可以更简单:

if str(s) == "quit":

Or: 要么:

if str(s) is "quit":

The == True is meaningless either == False you can use not more pythonicly. == True毫无意义,或者== Falsenot更多地使用Python。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM