If I have one element one, this is easy:
>>> 3 not in [2, 3, 4] False >>> 3 not in [4, 5, 6] True
But what if I have two lists and need to check if there are items in list A in list B ?
A
B
A=[1,2,3,4] B=[4,5,6,7]
How do I get a result showing that 1 , 2 , 3 not on list B ?
1
2
3
List Usage:
true answer
any([True for x in [1, 2, 3, 4] if x in [4, 5, 6, 7]])
list of items not in the second list
[x for x in [1, 2, 3, 4] if x not in [4, 5, 6, 7]]
if the items in the list are hashed:
>>> set(A) - set(B) {1, 2, 3}
otherwise you can use filter :
filter
>>> list(filter(lambda a: a not in B, A)) [1, 2, 3]
in this case, if sorting is B , you can get better performance using bisect.bisect_left to search by logarithm:
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]
You can also use list comprehension:
C=[i for i in A if i not in B]
Output:
[1, 2, 3]
You can use set .
set
eg.
>>> a=[1,2,3,4] >>> b=[4,5,6,7] >>> list(set(a)-set(b)) [1, 2, 3] >>>
set(A).difference(B) # set operation for difference between two collections A and B
This is a typical case for Boolean operations on sets:
zerotonine = set(range(10)) fourtoten = set(range(4,11)) print "exclusively in one:", zerotonine ^ fourtoten exclusively in one: set([0, 1, 2, 3, 10])
Source: https://habr.com/ru/post/989274/More articles:Regex.test () gives true false sequence? - javascriptSSRS Expanded reports disabled parameters in IE, and those without parameters simply return a blank screen - internet-explorerLink Swift enum member without an associated value - enumsJava RESTful Webservice CRUD Opreation Using Netbeans IDE - javaAndroid: crash after cropping image when updating OS version to 5.1.1 - androidIs there any way to do div rendering from right to left HTML - javascriptAre LAPACK streams supported? - multithreadingC ++ Virtual Memory Platform - c ++Search for all keys matching one value in std :: unordered_map - c ++How to convince SQL Server 2008r2 to use clr v4.0 instead of v2.0? - .netAll Articles