2011-04-12 45 views
38

例如,我有兩個列表python中的數組過濾器?

A   = [6, 7, 8, 9, 10, 11, 12] 
subset_of_A = [6, 9, 12]; # the subset of A 


the result should be [7, 8, 10, 11]; the remaining elements 

有沒有在Python內置函數來做到這一點?

回答

57

如果訂單不重要,您應該使用set.difference。但是,如果你想保持秩序,只需簡單的列表理解。

result = [a for a in A if a not in subset_of_A] 

編輯:作爲delnan說,性能會大幅如果subset_of_A是一個實際的set,改善,因爲在一個set成員資格檢查是O(1)相比,爲O(n)爲一個列表。

A = [6, 7, 8, 9, 10, 11, 12] 
subset_of_A = set([6, 9, 12]) # the subset of A 

result = [a for a in A if a not in subset_of_A] 
+12

而這可以通過使'subset_of_A'成爲一個真正的'set',它給出'O(1)'成員測試(而不是'O(n)'作爲與列表)。 – delnan 2011-04-12 19:47:47

+0

好點..... – 2011-04-12 23:00:36

2

如何

set(A).difference(subset_of_A) 
20

是的,filter功能:

filter(lambda x: x not in subset_of_A, A) 
+1

請注意,在Python 2中,'filter'返回列表本身,而在Python 3中,它返回一個迭代器。 – modulitos 2017-10-02 01:54:56

4

tuple(set([6, 7, 8, 9, 10, 11, 12]).difference([6, 9, 12]))

+0

呵呵,這個人得到了一個很酷的投票 – deepelement 2015-12-06 17:31:19

1
>>> a = set([6, 7, 8, 9, 10, 11, 12]) 
>>> sub_a = set([6, 9, 12]) 
>>> a - sub_a 
set([8, 10, 11, 7]) 
4

set(A)-set(subset_of_A)給你想要的結果集,但不會保留原來的訂購。以下是保序:

[a for a in A if not a in subset_of_A] 
2

使用Set類型:

A_set = Set([6,7,8,9,10,11,12]) 
subset_of_A_set = Set([6,9,12]) 

result = A_set - subset_of_A_set 
3

這只是問了前兩天(但我無法找到它):

>>> A = [6, 7, 8, 9, 10, 11, 12] 
>>> subset_of_A = set([6, 9, 12]) 
>>> [i for i in A if i not in subset_of_A] 
[7, 8, 10, 11] 

它取決於上下文,從一開始可能會更好地使用set。然後你可以使用set operations像其他答案顯示。

但是,僅將列表轉換爲集合並僅返回這些操作比列表理解更慢。

1
>>> A   = [6, 7, 8, 9, 10, 11, 12] 
>>> subset_of_A = [6, 9, 12]; 
>>> set(A) - set(subset_of_A) 
set([8, 10, 11, 7]) 
>>> 
5

沒有,是在Python函數沒有建立這樣做,因爲簡單地說:

set(A)- set(subset_of_A) 

將爲您提供答案。

+0

雖然這適用於他的示例,但如果元素在列表A中重複出現,可能會出現問題。 – 2014-09-20 14:31:50