[英]“list index out of range” exception (Python3)
当我检查列表的长度时,我一直在获取列表索引超出范围的异常。 第二个if
语句的if
或elif
部分会弹出错误,具体取决于用户输入的内容。 我知道当用户输入被分割时,该列表是正确创建的,因为我将其打印出来了...所以我对为什么会收到该错误有些困惑。
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
毫无意义,或者== False
您not
更多地使用Python。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.