[英]Why do I get an 'IndexError: list index out of range' when I try to remove a record from my list in the except block
當我嘗試運行此函數時,出現索引錯誤:列表超出范圍。 當我嘗試使用list.remove(list[i])
時,錯誤發生在代碼的except塊中。 不知道為什么我會超出范圍的錯誤,任何幫助將不勝感激!
我已經嘗試過使用函數周圍的各種打印語句進行調試,並且我發現我的記錄很好,每當我嘗試刪除except塊中的記錄時,它只會拋出此錯誤。
def subnet_insertion_sort(list):
with open('bad_subnets.csv', 'w') as z:
# Traverse through 1 to len(list)
for i in range(1, len(list)):
# extracts subnet from current list observed in list
# and casts it as a ip_network objects
try:
key_subnet = ipaddress.ip_network(unicode(list[i][0]))
j = i - 1
# Move elements of list[0..i-1], that are
# greater than key, to one position ahead
# of their current position
while (j >= 0 and key_subnet < ipaddress.ip_network(unicode(list[j][0]))):
temp = list[j]
list[j] = list[j + 1]
list[j + 1] = temp
j -= 1
except:
print("invalid subnet found: " + list[i][0] + " on line " + str(i) + ". It has been added to bad_subnets.csv")
writer_z = csv.writer(z)
writer_z.writerow(list[i])
list.remove(list[i])
continue
return list
我的預期結果是該函數正常運行,並且我收到了一個沒有無效子網的列表,但是我的實際輸出是索引錯誤:列表超出范圍。
一旦您開始for循環
for i in range(1,len(list))
如果原始列表的長度為10
,它將轉換為
for i in range(1,10)
如果在循環中從列表中刪除項目,則不會更改范圍。 一旦范圍超過當前列表的長度,將導致索引錯誤。
從不更改列表,而是創建一個新列表:
def subnet_insertion_sort(ipaddresses):
valid_addresses = []
with open('bad_subnets.csv', 'w') as z:
writer_z = csv.writer(z)
for i, address in enumerate(ipaddresses):
try:
key_subnet = ipaddress.ip_network(address)
except ValueError:
print("invalid subnet found: {} on line {} It has been added to bad_subnets.csv".format(address, i)
writer_z.writerow(address)
else:
valid_addresses(key_subnet)
return sorted(valid_addresses)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.