如何从Python中的大列表中删除曾经使用过的列表中的项目以节省内存?

vik*_*iky 0 python loops memory-management python-3.x

如果我有一个包含数百万个项目的大型列表,我想迭代它们中的每一个。一旦我使用了该项目,它将永远不会再次使用,那么如何从使用过的列表中删除该项目呢?最好的方法是什么?我知道 numpy 快速且高效,但想知道如何使用普通列表来完成它。

mylst = [item1, item2,............millions of items]
for each_item in mylist:
    #use the item
    #delete the item to free that memory
Run Code Online (Sandbox Code Playgroud)

Tim*_*ers 5

您无法在 Python 中直接删除对象 - 当不再可能引用对象时,对象的内存会通过垃圾回收自动回收。只要对象列表中,就可以稍后再次引用它(通过列表)。

所以你也需要销毁该列表。例如,像这样:

while mylst:
    each_item = mylst.pop()  # removes an object from the end of the list
    # use the item
Run Code Online (Sandbox Code Playgroud)