python - 当我尝试从 except 块中的列表中删除记录时,为什么会出现“IndexError: list index out of range”
问题描述
当我尝试运行此函数时,我收到一个索引错误:列表超出范围。当我尝试使用list.remove(list[i])
. 不知道为什么我得到超出范围的错误,任何帮助将不胜感激!
我已经尝试在我的函数周围使用各种打印语句进行调试,并且我看到我的记录很好,只要我尝试删除我的 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)
如果您从循环中的列表中删除项目,则不会更改范围。一旦范围超过当前列表的长度,就会导致索引错误。
推荐阅读
- google-bigquery - 如何在 Google Big Query 上将特定列数据传输到 table1 到 table2
- arrays - 如何更新 React 组件中的 map() 变量,onclick?
- laravel - 在 Laravel 中初始化 FullCalendar
- javascript - 重构嵌套事件监听器?
- python - 如何让matplotlib条形图超出边界,所以我必须平移才能看到图形的其余部分?
- r - 修改优势比的 ggplot
- swift - 带有 UIBezierPath 的圆形表冠
- python - 无法通过外部 css 影响 html 的外观
- reactjs - 如何使用 Dockerfile/Nginx/Heroku 公开 1 个以上的端口
- sql-server - 将数据从电子表格导入数据库,无需主键