Python:列表索引超出范围错误
我在以下行中得到此错误:Python:列表索引超出范围错误,python,error-handling,Python,Error Handling,我在以下行中得到此错误:if行[0]。startswith(元素): 我不知道为什么会出现这个错误。有人能帮忙吗。多谢各位 f = open ('testLC31.txt', 'r') lineCount = 0 toIgnore = ["AND", "ADD", "LEA", "PUTS", "JSR", "LD", "JSRR" , "NOT", "LDI" , "LDR", "ST", "STI", "STR", "BR" , "JMP", "TRAP" , "J
if行[0]。startswith(元素):
我不知道为什么会出现这个错误。有人能帮忙吗。多谢各位
f = open ('testLC31.txt', 'r')
lineCount = 0
toIgnore = ["AND", "ADD", "LEA", "PUTS", "JSR", "LD", "JSRR" , "NOT", "LDI" ,
"LDR", "ST", "STI", "STR", "BR" , "JMP", "TRAP" , "JMP", "RTI" ,
"BR", "ST", "STI" , "STR" , "BRz", "BRn" , "HALT"]
label = []
instructions = []
i = 0
for line in f:
line = line.split()
for element in toIgnore:
if line[0].startswith(element):
lineCount += 1
else:
label.append(line[0])
instructions.append(line[1])
i += 1
lineCount += 1
示例文件:
.ORIG x3000
AND R0, R0, #0
AND R1, R1, #0
AND R2, R2, #0
AND R7, R7, #0
LEA R0, MSG1
PUTS
LEA R1, MEMORYSPACE
JSR STRNG
LD R0, NEWLINE
OUT
ADD R0, R1, #0
LD R2, NEG48
ADD R0, R0, R2
PUTS
HALT
MSG1 .STRINGZ "Input a string (length <= 9): "
MEMORYSPACE .BLKW 9
NEWLINE .FILL #10
NEG48 .FILl #-48
.END
.ORIG x3000
和R0,R0,#0
R1,R1,#0
R2,R2,0
和R7,R7,#0
LEA R0,MSG1
放
lear1,记忆空间
JSR STRNG
新线
出来
加上R0,R1,#0
LD R2,NEG48
加上R0,R0,R2
放
停止
MSG1.STRINGZ“输入字符串(长度导致索引超出范围错误的原因是”。split()
会导致空列表[]
。因此,当读取空行时,会导致空列表行,以及列表[0]
会导致超出范围的错误。这有一些问题,我不知道您的要求是什么,因此这是一种方法。但是您为每个不在忽略列表中的实例添加了完全相同的单词,因此会有大量重复。如果您希望删除该单词,请让我知道,我可以为您添加
for line in f:
if line.split(): #check to see if it is actually something that can be split
elem = line.split()
if len(elem) > 1: #check to see that its more than one word if its not then you are on one of the ignore words
for element in toIgnore:
if elem[0].startswith(element):
lineCount += 1
else:
label.append(elem[0])
instructions.append(elem[1])
i += 1
lineCount += 1
如果您想在列表中有唯一的说明,那么您可以这样做
f = open ('testLC31.txt', 'r')
line_count = 0
to_ignore = ["AND", "ADD", "LEA", "PUTS", "JSR", "LD", "JSRR" , "NOT", "LDI" ,
"LDR", "ST", "STI", "STR", "BR" , "JMP", "TRAP" , "JMP", "RTI" ,
"BR", "ST", "STI" , "STR" , "BRz", "BRn" , "HALT"]
label = []
instructions = []
i = 0
for line in f:
elem = line.split() if line.split() else ['']
if len(elem) > 1 and elem[0] not in to_ignore:
label.append(elem[0])
instructions.append(elem[1])
i += 1
line_count += 1
elif elem[0] in to_ignore:
line_count += 1
文件中有空行吗?首先,在循环中打印一行,看看它是什么,然后输出一个if line.strip()
若要捕获空行并使用和
一起打开或至少关闭文件,您的代码有一些问题…因此,首先…可以拆分一行,\n该行不会返回空数组。您还有其他行只有一个字,并且只能拆分一次,因此行[1]将失败。@Chalupa在修复行[0]后错误您到达另一个…当单词本身有PUTS时…line.split()工作正常,并且它不是忽略列表中的第一项,因此当您附加指令行[1]时,它到达else它不存在我确实需要唯一的元素,但这不会更新包含单词的行的行数toIgnore@Chalupa当您的元素在忽略列表中时,请参阅我的编辑以保留行数。我还更改了变量/对象以使用接受的python对象命名约定