简体   繁体   English

Python list.remove(x)2.7.5

[英]Python list.remove(x) 2.7.5

I have two lists shown below. 我有以下两个列表。 I'm trying to use the list.remove(x) function to remove the files that are in both list1 and list2, but one of my lists has file extensions while the other does not! 我正在尝试使用list.remove(x)函数删除list1和list2中的文件,但是我的一个列表具有文件扩展名,而另一个列表没有文件扩展名! What should be my approach!? 我该怎么办!!

List1 = ['myfile.v', 'myfile2.sv', 'myfile3.vhd', 'etcfile.v', 'randfile.sv']
List2 = ['myfile', 'myfile2', 'myfile3']

#This is in short what I would like to do, but the file extensions throw off
#the tool!
for x in List2:
   List1.remove(x)

Thanks! 谢谢!

It's really dangerous to loop over a list as you are removing items from it. 当您从列表中删除项目时,遍历列表确实很危险。 You'll nearly always end up skipping over some elements. 您几乎总是会跳过某些元素。

>>> L = [1, 1, 2, 2, 3, 3]
>>> for x in L:
...     print x
...     if x == 2:
...         L.remove(2)
... 
1
1
2
3
3

It's also inefficient, since each .remove is O(n) complexity 这也是低效的,因为每个.remove都是O(n)复杂度

Better to create a new list and bind it back to list1 最好创建一个新列表并将其绑定回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]

or for an "inplace" version 或“就地”版本

list1[:] = [x for x in list1 if os.path.splitext(x)[0] not in set2]

for a truly inplace version as discussed in the comments - doesn't use extra O(n) memory. 注释中讨论的真正原位版本-不使用额外的O(n)内存。 And runs in O(n) time 并在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']

For the sake of it, if you want to use the list.remove(element) , as it is very easy to read for others, you can try the following. 为此,如果您想使用list.remove(element) ,因为它很容易为他人阅读,则可以尝试以下操作。 If you have a function f that returns true if the value is correct/passes certain tests as required, 如果您有一个函数f,该函数在值正确/根据需要通过某些测试后返回true,

Since this will NOT work: 由于这将不起作用:

def rem_vals(L):
    for x in L:
        if not f(x):
             L.remove(x)

for more than one value to be removed in the list L, we can use recursion as follows: 对于要在列表L中删除的多个值,我们可以如下使用递归:

def rem_vals_rec(L):
    for x in L:
        if not f(x):
            L.remove(x)
            rem_vals_rec(L)

Not the fastest, but the easiest to read. 不是最快,但最容易阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM