当您从列表中删除项目时,循环遍历列表非常危险。你几乎总是会跳过一些元素。
>>> L = [1, 1, 2, 2, 3, 3]
>>> for x in L:
... print x
... if x == 2:
... L.remove(2)
...
1
1
2
3
3
这也是低效的,因为每个.remove
都是 O(n) 复杂度
最好创建一个新列表并将其绑定回list1
import os
list1 = ['myfile.v', 'myfile2.sv', 'myfile3.vhd', 'etcfile.v', 'randfile.sv']
list2 = ['myfile', 'myfile2', 'myfile3']
set2 = set(list2) # Use a set for O(1) lookups
list1 = [x for x in list1 if os.path.splitext(x)[0] not in set2]
或“就地”版本
list1[:] = [x for x in list1 if os.path.splitext(x)[0] not in set2]
对于评论中讨论的真正就地版本 - 不使用额外的 O(n) 内存。并在 O(n) 时间内运行
>>> list1 = ['myfile.v', 'myfile2.sv', 'myfile3.vhd', 'etcfile.v', 'randfile.sv']
>>> p = 0
>>> for x in list1:
... if os.path.splitext(x)[0] not in set2:
... list1[p] = x
... p += 1
...
>>> del(list1[p:])
>>> list1
['etcfile.v', 'randfile.sv']