【问题标题】:"list index out of range" exception (Python3)“列表索引超出范围”异常(Python3)
【发布时间】:2016-09-11 04:33:42
【问题描述】:

当我检查列表 a 的长度时,我不断收到列表索引超出范围异常。第二个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)

【问题讨论】:

  • 什么是第一?
  • 这是我创建的另一种方法。错误在它被调用之前弹出,所以我只是想在修复这个错误时它不相关。
  • 你想要做什么。 ** if (str(s) is "quit") == True:**
  • 如果用户输入“退出”,系统就会退出……你知道你并没有真正帮助回答问题
  • 你的代码没问题。这里的问题不是您粘贴的内容。请发布first函数

标签: python list


【解决方案1】:

问题似乎是first() 的定义。您将其作为函数调用:

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

但是你把它定义为一个方法:

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

命令和参数数组被放入selfa 始终是一个空列表,您尝试对其进行索引并失败。此外,除非您确定自己在做什么,否则不应使用像 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 方法,如果word 是附加的,那么后面应该有2 个输入,所以我认为最好使用列表而不是字符串;即因为你不知道会输入多少字
【解决方案2】:

真正的问题:

要解决您的错误,您必须删除first 函数的self 参数

def first(a=list())

self基本上只用于面向对象的创建方法。 像你这样的函数不能使用 self 否则你会将第一个参数传递给 self 而不是你想要的。

我要指出的第二个问题是,您正在尝试使用 isstringfunction 之间进行比较。

 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 是没有意义的== False 你可以使用not 更pythonicly。

【讨论】:

  • 请注意,str(s) == "quit"str(s) is "quit" 是根本不同的比较。见stackoverflow.com/questions/1504717/…
  • 好的,但是为什么当用户输入诸如“delfile oirgorhgoe”之类的其他内容(最终将删除名为 oirgorhgoe 的文件)和列表 a 的长度(在 s 拆分后)时出现错误是否检查了“delfile oirgorhgoe”?
  • @GabbyFreeland 刚刚测试了您的代码,我认为第一个函数是这里的问题。
  • @GabbyFreeland 你能把错误信息贴在这里吗?
  • 我刚刚发布了第一个函数。错误是Traceback (most recent call last): File "E:\COMPSCI 340\CS340 A2\TinyDOS.py", line 10, in &lt;module&gt; class TinyDOS(): File "E:\COMPSCI 340\CS340 A2\TinyDOS.py", line 74, in TinyDOS if (len(a) is 2): first(a) File "E:\COMPSCI 340\CS340 A2\TinyDOS.py", line 43, in first word = a[0] IndexError: list index out of range
猜你喜欢
  • 2018-07-05
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多