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

时间:2015-02-10 23:41:19

标签: python error-handling

我在行上收到此错误: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

2 个答案:

答案 0 :(得分:1)

索引超出范围错误的原因是"".split()导致空列表[]。因此,当读取空行时,它会导致空列表line,而list[0]会导致超出范围错误。

答案 1 :(得分:1)

这有一些问题,我不知道你的要求是什么,所以这是一种方法..但你为每个不在忽略列表中的实例添加完全相同的单词所以会有一个很多重复。如果你想要删除让我知道,我可以为你添加

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