python - 为什么程序成功第一步时出现 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()
解决方案
您在迭代列表时从列表中删除,这就是您收到 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')
推荐阅读
- python - 如何使用 Python 解决自动化 WhatsApp 中的问题
- reactjs - 在 Mac 上成功运行 react 时出错:ELIFECYCLE、spawn、ENOENT
- gradle - 如何从命令行获取 gradle 属性?
- java - 模拟或覆盖静态方法来测试一个类
- spring - 如何使用 Spring Data 在 mongodb 中获取字段值列表作为结果
- list - 将每个项目与列表的其余项目进行比较
- sql-server - 必须用更新百分比声明标量变量
- azure - 是否可以通过 ARM 模板在 Azure SQL 中预配非管理用户?
- java - 在 Spring Boot 中创建一个 Couchbase 配置类,使用数据表单 application.properties?
- algorithm - 算法的最佳情况