首页 > 解决方案 > 当我尝试从 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

我的预期结果是该函数运行正常,并且我收到了一个没有无效子网的列表,但我的实际输出是索引错误:列表超出范围。

标签: pythonlistfor-loopif-statementtry-catch

解决方案


一旦你开始你的 for 循环

for i in range(1,len(list))

如果您的原始列表的长度是10,它将转换为

for i in range(1,10)

如果您从循环中的列表中删除项目,则不会更改范围。一旦范围超过当前列表的长度,就会导致索引错误。


推荐阅读