Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 迭代列表时从列表中删除项目_Python_List_Loops_Iteration - Fatal编程技术网

Python 迭代列表时从列表中删除项目

Python 迭代列表时从列表中删除项目,python,list,loops,iteration,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

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

下面是一个非常简单的例子:

>>> 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的解决方法吗?

你可以跟踪所有需要删除的索引,然后删除它们

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
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]

你到底想实现什么?这些项目是真实的URL。我想对所有这些URL做一些事情(获取一些数据)。但有时也会出现连接中断或类似问题的情况。为了能够从出现问题的url继续,我必须将它们保存到文件中。那么,为什么需要在迭代列表时从列表中删除项目呢?首先要找到所有url。这些URL将写入文件中。下一步是处理每个URL,以便逐个加载和处理URL。当url被处理时,它会从列表中删除,因为我不想处理它两次,并且列表会被保存,以便脚本知道在连接出现问题时从何处开始。顺序重要吗?你能不能只
pop
每一个?这有完全相同的问题,索引会随着你删除东西而移动!