python del在使用循环后删除了txt中的错误行

2024-05-19 12:37:08 发布

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

我正在试图删除列表中的“line1”、“line4”和“line5”。但结果不是我所期望的。你知道吗

item =  ['line1',
'line2',
'line3',
'line4',
'line5',
'line6',
'line7',
'line8']

removeLine = [0,1,3,5]

for x, y in grouped(sorted(removeLine), 2):
    print x,y
    del item[x:y]

print item

>>> ['line2', 'line3', 'line4', 'line7', 'line8']

但我的预期结果是

>>> ['line2', 'line3', 'line7', 'line8']

希望有人能给我一些建议。非常感谢你。你知道吗


Tags: in列表foritemprintline1groupedline2
1条回答
网友
1楼 · 发布于 2024-05-19 12:37:08

You can make use of the enumerate function to achieve this:

my_list = ['0','1','2','3','4','5']
index_to_delete = [0,3,4]

for i,j in enumerate(index_to_delete): #Groups indices with numbers
    del my_list[j-i] #After every deletion i increases to account for lost index
>>>print(my_list)
['1', '2', '5']

从这一点你得到了一个总的想法,你需要保持删除以及跟踪。因此,每次删除后,要删除的索引都会被缩减以应对删除。你知道吗

这可以通过多种方式完成,使用enumerate对我来说似乎是最简单的情况,我没有修改代码来完成您的工作,因为它留给您来实现,因为现在您已经有了完成它的一般想法。

相关问题 更多 >