[英]Python list.remove(x) 2.7.5
我有以下兩個列表。 我正在嘗試使用list.remove(x)函數刪除list1和list2中的文件,但是我的一個列表具有文件擴展名,而另一個列表沒有文件擴展名! 我該怎么辦!!
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)
謝謝!
當您從列表中刪除項目時,遍歷列表確實很危險。 您幾乎總是會跳過某些元素。
>>> 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']
為此,如果您想使用list.remove(element)
,因為它很容易為他人閱讀,則可以嘗試以下操作。 如果您有一個函數f,該函數在值正確/根據需要通過某些測試后返回true,
由於這將不起作用:
def rem_vals(L):
for x in L:
if not f(x):
L.remove(x)
對於要在列表L中刪除的多個值,我們可以如下使用遞歸:
def rem_vals_rec(L):
for x in L:
if not f(x):
L.remove(x)
rem_vals_rec(L)
不是最快,但最容易閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.