[英]How to check if an element from List A is not present in List B in Python?
如果我單獨使用一個元素,這很容易:
>>> 3 not in [2, 3, 4] False >>> 3 not in [4, 5, 6] True
但是如果我有兩個列表並且必須檢查列表A
的元素是否出現在列表B
呢?
A=[1,2,3,4]
B=[4,5,6,7]
我如何得到一個結果,顯示我, 1
, 2
, 3
不在列表中B
?
如果列表中的項目是可清除的 :
>>> set(A) - set(B)
{1, 2, 3}
否則,您可以使用filter
功能:
>>> list(filter(lambda a: a not in B, A))
[1, 2, 3]
在這種情況下,如果B
已排序 ,您可以通過使用bisect.bisect_left
以對數方式搜索來獲得更好的性能:
>>> def pred(a): # if B is already *sorted*
... from bisect import bisect_left
... i = bisect_left(B, a)
... return i == len(B) or B[i] != a
...
>>> list(filter(pred, A))
[1, 2, 3]
您還可以使用列表理解:
C=[i for i in A if i not in B]
輸出:
[1, 2, 3]
使用列表理解:
真實的答案
any([True for x in [1, 2, 3, 4] if x in [4, 5, 6, 7]])
第二個列表中不存在的元素列表
[x for x in [1, 2, 3, 4] if x not in [4, 5, 6, 7]]
這是集合上布爾運算的典型情況:
zerotonine = set(range(10))
fourtoten = set(range(4,11))
print "exclusively in one:", zerotonine ^ fourtoten
exclusively in one: set([0, 1, 2, 3, 10])
set(A).difference(B) # set operation for difference between two collections A and B
你可以使用set
。
例如
>>> a=[1,2,3,4]
>>> b=[4,5,6,7]
>>> list(set(a)-set(b))
[1, 2, 3]
>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.