[英]How to filter the list elements within list based on another list in python?
[英]How to filter a list based on elements in another list in python
我有一個大約62,000個數字的列表A,另一個大約370,000個列表B。 我想過濾B,使其只包含來自A的元素。我嘗試過這樣的事情:
A=[0,3,5,73,88,43,2,1]
B=[0,5,10,42,43,56,83,88,892,1089,3165]
C=[item for item in A if item in set(B)]
哪個可行,但是對於這么大的列表顯然很慢,因為(我認為嗎?)搜索會遍歷整個B,即使已經在B中找到了該元素也是如此。因此腳本正在遍歷370,000個元素的列表62,000次。
A和B中的元素是唯一的(B包含0到700,000之間的唯一值的列表,而A包含這些值的唯一子集),因此一旦在B中找到A [i],搜索就可以停止。 值也按升序排列(如果有任何意義)。
有什么辦法可以更快地做到這一點?
這將為A中的每個項目創建一個新的set(B)
。相反,請使用內置的set.intersection
:
C = set(A).intersection(B)
為了確保我所做的是最快的,我會這樣做:
A=[0,3,5,73,88,43,2,1]
B=[0,5,10,42,43,56,83,88,892,1089,3165]
B_filter = B.copy()
C = []
for item in A:
if filter in B_filter:
C.append(item)
B_filter.pop(0) # B_filter is a list, and it's in ascending order so always the first
如果您不擔心丟失B
列表,則可以使用B
代替B_filter
而不聲明B_filter
,因此不必復制370k大列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.