首页 > 解决方案 > 为什么程序成功第一步时出现 IndexError?

问题描述

我试图制作排序器,删除第一个列表中 IP 的重复项并将其保存到文件中,但在第一轮成功后,它给了我 IndexError: list index out of range。

我期待正常的排序过程,但它不起作用

代码:

ip1 = open('hosts', 'r')
ip2 = open('rotten', 'r')
ipList1 = [line.strip().split('\n') for line in ip1]
ipList2 = [line.strip().split('\n') for line in ip2]
for i in range(len(ipList1)):
    for a in range(len(ipList2)):
        if(ipList1[i] == ipList2[a]):
            print('match')
            del(ipList1[i])
            del(ipList2[a])
            i -= 1
            a -= 1
c = open('end', 'w')
for d in range(len(ipList1)):
    c.write(str(ipList1[d]) + '\n')
c.close()

标签: pythonpython-3.xlistsorting

解决方案


您在迭代列表时从列表中删除,这就是您收到 IndexError 的原因。

使用sets可以更轻松地完成此操作:

with open('hosts') as ip1, open('rotten') as ip2:
    ipList1 = set(line.strip().split('\n') for line in ip1)
    ipList2 = set(line.strip().split('\n') for line in ip2)

good = ipList1 - ipList2

with open('end', 'w') as c:
    for d in good:
        c.write(d + '\n')

推荐阅读