当程序迈出成功的第一步时,为什么我有索引器?

2024-06-26 15:00:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着让sorter删除第一个列表中重复的IP并将其保存到一个文件中,但在第一轮成功后,它给了我Indexer:列表索引超出范围

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

代码:

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()

Tags: in列表forlenlinerangeopensplit
3条回答

你一下子改变了名单。例如,For expression获取长度为5个元素的列表,在第一次迭代后删除4个元素,因此在For的第二次迭代中,尝试提取第二个元素,但现在它不存在。
如有必要,保存顺序,可以使用生成器表达式:

ips = [ip for ip in ipList1 if ip not in set(list2)]

如果没有,就使用集合表达式

您不应该修改当前正在迭代的列表。 一个解决方案就是创建第三个列表来保存非重复项。另一种方法是只使用集合,然后将它们彼此相减,尽管我知道您是否喜欢一个列表中的重复项。此外,您现在的做法是,只有在其位于同一索引时,才会发现重复项

ip2 = open('rotten', 'r')
ipList1 = [line.strip().replace('\n', '') for line in ip1]
ipList2 = [line.strip().replace('\n', '') for line in ip2]
ip1.close()
ip2.close()
newlist = []
for v in ip1:
    if v not in ip2:
        newlist.append(v)

c = open('end', 'w')
c.write('\n'.join(newlist))
c.close()

您在迭代列表时从列表中删除,这就是为什么会得到一个索引器

使用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')

相关问题 更多 >