Python: 列表索引超出范围错误

Python: list index out of range error

我在线上收到此错误:if line[0].startswith(element): 我不知道为什么会收到此错误。谁能帮忙。谢谢你。

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

您得到索引超出范围错误的原因是 "".split() 导致空列表 []。因此,当读取一个空行时,它会导致空列表 line,而 list[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