Reputation: 8144
I have a two list of objects say example
L1 = [2,3,4]
L2 = [1,2]
i want to have two different list.
1) matching items 2) not matching items
I am able to get the matching element #1 like below
match = [x for x in L1 if x in L2]
but how can i get the not matching elements in a efficient way.
I can use not in but is there any other way of doing this.
Thanks ,
Upvotes: 3
Views: 332
Reputation: 69755
I think you can take advantage of the built-in type set
which basically has unordered distinct elements. I also encourage you to try the shorthand notation to perform the operations union
, intersection
, and difference
.
>>> s1 = set(L1)
>>> s2 = set(L2)
>>> s1 | s2 # union
{1, 2, 3, 4}
>>> s1 & s2 # intersection
{2}
>>> s1 - s2 # difference
{3, 4}
>>> s1 ^ s2 # symmetric difference
{1, 3, 4}
Suppose A
and B
are sets.
A∪B = {x: x ∈ A or x ∈ B}
A∩B = {x: x ∈ A and x ∈ B}
A-B = {x: x ∈ A and x ∉ B}
A∆B = A∪B - A∩B
Upvotes: 0
Reputation: 10223
By List compression:
>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i not in L2]
[3, 4]
>>> [i for i in L1 if i in L2]
[2]
>>> [i for x in L2 if i not in L1]
[1]
>>> [i for i in L1 if i not in L2] + [i for i in L2 if i not in L1]
[3, 4, 1]
Upvotes: 1
Reputation: 113
Here's a possibility:
not_match=[x for x in L1 if x not in L2] + [x for x in L2 if x not in L1]
Upvotes: 1
Reputation: 34146
You can get it by using match
:
no_match = [x for x in L1 + L2 if x not in match]
Upvotes: 1
Reputation: 117876
You can use the various set
methods such as intersection
, difference
, symmetric_difference
, and union
>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> set(L1).intersection(L2)
{2}
>>> set(L1).difference(L2)
{3, 4}
>>> set(L1).symmetric_difference(L2)
{1, 3, 4}
>>> set(L1).union(L2)
{1, 2, 3, 4}
Upvotes: 3