当我尝试从except块中的列表中删除记录时,为什么会出现'IndexError:list index out of range'

问题描述 投票:0回答:2

当我尝试运行此函数时,我得到一个索引错误:列表超出范围。当我尝试使用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

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

python list for-loop if-statement try-catch
2个回答
3
投票

一旦你开始你的for循环

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

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

for i in range(1,10)

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


0
投票

永远不要更改列表,而是创建一个新列表:

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)
© www.soinside.com 2019 - 2024. All rights reserved.