【发布时间】:2026-02-04 05:05:01
【问题描述】:
我尝试制作排序器,删除第一个列表中 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()
【问题讨论】:
-
你的'for'循环不是pythonic和过于复杂。在 Python 中,您只需遍历元素,如果您确实需要索引,请使用 'for idx, element in enumerate(iterable):'
标签: python python-3.x list sorting