Python - list.remove 在列表上迭代时

标签 python arrays directory removeall

<分区>

在 python 中,我遇到了 list.remove 方法的问题。它并没有删除逻辑上必须存在的内容,并且在列表中留下了大量内容。

import os

def removeAll(content):
        for afile in content:
            content.remove(afile)
        return content
content = removeAll(os.listdir("C:\\Windows\\System32"))
print(content)

但是如果我要在没有循环的情况下删除单个内容

content.remove(content[123]) #If this string hasn't already been removed.

它会起作用的。 这是为什么?处理庞大列表的理想替代方案是什么?

最佳答案

这不是错误。参见 Remove items from a list while iterating关于如何完美地做到这一点。

列表是一种可变数据类型。如果从中删除元素,列表的长度(可能还有元素的索引)将会改变。在您的第二个示例中,如果您在删除前后打印内容的长度,您会看到差异,因为您没有假设旧索引和长度对列表有效。


考虑以下示例以了解有关何时发生此异常的更多信息:

>>> content = range(4)
>>> content
[0, 1, 2, 3]
>>> len(content)
4
>>> count = 0
>>> length = len(content)
>>> while count < length:
...     print count, length, content, len(content)
...     content.remove(content[count])
...     count += 1
... 
0 4 [0, 1, 2, 3] 4
1 4 [1, 2, 3] 3
2 4 [1, 3] 2
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
IndexError: list index out of range

很明显,您要迭代的长度是一个常数,但 count 的值只是对应于列表中不再存在的索引位置。


要解决列表的这种可变性质,您可以从列表的末尾删除元素:

>>> content = range(4)
>>> count = len(content) - 1
>>> while count >= 0:
...     print count, length, content, len(content)
...     content.remove(content[count])
...     count -= 1
... 
3 4 [0, 1, 2, 3] 4
2 4 [0, 1, 2] 3
1 4 [0, 1] 2
0 4 [0] 1
>>> print content
[]

或者您可以始终pop/remove 第一个元素,正如其他答案所指出的那样。

关于Python - list.remove 在列表上迭代时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29586534/

相关文章:

python - numpy 中的行专业和列专业是什么?

.net - 如何在 .NET 中复制文件夹以及所有子文件夹和文件?

python - 类型错误 : '_sre.SRE_Match' object has no attribute '__getitem__'

python - 删除包含 2 列子集的重复项,但另一列必须不同?

arrays - NSView 从 super View 中删除一些 subview

php - 在数组 php 中搜索信息时缩短脚本

c++ - Qt 中的文件选择

android - 检查文件夹是否为空(内部存储)

python - 如何在 PostgreSQL 中将整数解压缩为 float ?

javascript - 在 1 级深度上翻转键值对