gpt4 book ai didi

python - Python : list index out of range error

转载 作者:行者123 更新时间:2023-12-03 08:13:01 26 4
gpt4 key购买 nike

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

最佳答案

这个有一些问题,我不知道您的要求是什么,所以这是一种方法..但是您要为每个实例添加完全相同的单词,因为它不在忽略列表中,所以会有很多重复项。如果您希望删除该邮件,请告诉我,我可以为您添加

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

关于python - Python : list index out of range error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28444012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com