在迭代期间删除python列表的元素

时间:2013-02-13 19:56:28

标签: python optimization garbage-collection

我在每个元素上都有一个非常大的列表,我必须做很多操作。实质上,列表的每个元素以各种方式附加,然后用于生成对象。然后使用这些对象生成另一个列表。

不幸的是,以天真的方式执行此操作会占用所有可用内存。

我想做以下事情:

for a in b:
    # Do many things with a
    c.append(C(modified_a))
    b[b.index(a)] = None # < Herein lies the rub

这似乎违反了在迭代期间不应修改列表的想法。有没有更好的方法来进行这种手动垃圾收集?

3 个答案:

答案 0 :(得分:2)

这应该不是问题,因为您只是为列表元素分配新值,而不是真正删除它们。

但是不应该使用索引方法搜索a,而应该使用枚举。

另见: http://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/ “首先,让我明确一点,在本文中,当我说”修改“时,我的意思是在列表中插入或删除项目。仅仅更新或改变列表项就可以了。”

答案 1 :(得分:0)

最好的选择是generator

def gen(b):
   for a in b:
      # Do many things with a
      yield a

此处正确完成,无需额外内存。

答案 2 :(得分:-1)

您的代码存在一些问题。

首先,将None分配给列表元素不会删除它:

>>> l=[1,2,3,4,5,6,6,7,8,9]
>>> len(l)
10
>>> l[l.index(5)]=None
>>> l
[1, 2, 3, 4, None, 6, 6, 7, 8, 9]
>>> len(l)
10

其次,使用索引来查找要更改的元素并不是完全有效的方法。

您可以使用枚举,但仍需要循环删除None值。

for i,a in enumerate(b):
    # Do many things with a
    b[i]=C(modified_a)
    b[i]=None 
c=[e for e in b if e is not None]

您可以使用列表推导将新的'a'值复制到c列表然后删除b:

c=[do_many_things(a) for a in b]
del b                              # will still occupy memory if not deleted...

或者,如果您希望b进行适当修改,可以使用slice assignment

b[:]=[do_many_things(a) for a in b]

切片分配以这种方式工作:

#shorted a list
>>> b=[1,2,3,4,5,6,7,8,9]
>>> b[2:7]=[None]
>>> b
[1, 2, None, 8, 9]

#expand a list
>>> c=[1,2,3]
>>> c[1:1]=[22,33,44]
>>> c
[1, 22, 33, 44, 2, 3]

# modify in place
>>> c=[1,2,3,4,5,6,7]
>>> c[0:7]=[11,12,13,14,15,16,17]
>>> c
[11, 12, 13, 14, 15, 16, 17]

你可以在列表理解中使用它,如下所示:

>>> c=list(range(int(1e6)))
>>> c[:]=[e for e in c if e<10]
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

其中一条评论指出切片分配并未完全修改;生成临时列表。 That is true.但是,让我们看看这里的总时间:

import time
import random
fmt='\t{:25}{:.5f} seconds' 
count=int(1e5)
a=[random.random() for i in range(count)]
b=[e for e in a]

t1=time.time()
for e in b:
    if e<0.5: b[b.index(e)]=None  
c=[e for e in b if e is not None]    
print(fmt.format('index, None',time.time()-t1))

b=[e for e in a]
t1=time.time()
for e in b[:]:
    if e<0.5: del b[b.index(e)]  
print(fmt.format('index, del',time.time()-t1))

b=[e for e in a]
t1=time.time()
for i,e in enumerate(b[:]):
    if e<0.5: b[i]=None
c=[e for e in b if e is not None]    
print(fmt.format('enumerate, copy',time.time()-t1))

t1=time.time()
c=[e for e in a if e<.5]
del a
print(fmt.format('c=',time.time()-t1))

b=[e for e in a]
t1=time.time()
b[:]=[e for e in b if e<0.5]
print(fmt.format('a[:]=',time.time()-t1))

在我的电脑上打印:

index, None              87.30604 seconds
index, del               28.02836 seconds
enumerate, copy          0.02923 seconds
c=                       0.00862 seconds
a[:]=                    0.00824 seconds

或者,如果没有帮助,请使用numpy获得更优化的数组选项。