我是python新手;我一直在JavaScript編碼,所以我不習慣我得到的所有錯誤。列表索引超出範圍錯誤,同時使用for循環中的if語句
我試圖用for循環將屬性添加到空對象,但我得到一個錯誤,指出列表索引超出範圍。當我在for循環中添加if語句時,該錯誤似乎正在發生。雖然我沒有使用索引來遍歷seat_info數組。請幫我理解爲什麼會發生這種情況,謝謝!
seats_info = ['\n1,133,0,A', '\n1,133,2,C', '\n1,133,1,B', '\n1,133,4,E', '\n1,133,3,D', '\n2,132,0,24', '\n2,132,1,25', '\n2,132,2,26']
def read_manifest(self, manifest):
file = manifest_dir + '/' + manifest
data = open(file, 'r')
seats_info = data.read().split('\r')[1:]
data.close()
self.seat_information = {}
for seat_info in seats_info:
one_seat = seat_info.split(',')
section_id = one_seat[0][1:]
one_seat.remove(one_seat[0])
one_seat.insert(0, section_id)
if one_seat[1] not in self.seat_information:
self.seat_information[one_seat[1]] = [one_seat]
else:
self.seat_information[one_seat[1]].append(one_seat)
Error Message that I received
Traceback (most recent call last):
File "path/normalizer.py", line 75, in <module>
normalizer.read_manifest(citifield)
File "path/normalizer.py", line 36, in read_manifest
if one_seat[1] not in self.seat_information:
IndexError: list index out of range
建議在此處僅使用print語句調試。文件格式可能會以一種微不足道的方式偏離您的期望。通過在你的循環中放置一個'print seat_info'或'print one_seat',你將會有更多的事情要做。 –
Javascript也會在訪問超出數組索引時拋出錯誤,是嗎? –
您有硬編碼的索引值,比如one_seat = seat_info.split(',') section_id = one_seat [0] [1:],並且seat_info.split(',')可能會返回一個數組範圍。檢查你的數據。建議在不確定的情況下使用try塊並處理異常 – slysid