迭代时从列表中删除项目

时间:2015-09-08 15:40:10

标签: python list loops iteration

我试图用项目迭代列表。处理项目时,我想删除该项目并将列表写入文件。但是存在一个问题,即只删除偶数位置上的项目。

这是一个非常简单的例子:

>>> x = [1,2,3,4,5,6,7,8,9]
>>> for i in x:
...     print x
...     x.remove(i)
...     write_x_into_the_file()
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 7, 8, 9]
[2, 4, 6, 8, 9]

我认为这是因为它使用索引递增进行迭代。你知道一些pythonic解决方法吗?

2 个答案:

答案 0 :(得分:0)

x = [1,2,3,4,5,6,7,8,9][::-1]
while len(x):
    ele = x.pop() # equv to ordinary for loop

x = [1,2,3,4,5,6,7,8,9]
while len(x):
    ele = x.pop() # reversed loop

答案 1 :(得分:-1)

您可以跟踪需要删除的所有索引,然后在

之后删除它们
delete = []
my_list = [1,2,3,4,5,6,7,8,9]
for i, x in enumerate(my_list):
    write_x_into_the_file()
    delete.append(i)

for d in delete:
    del my_list[d]