DanielSon
DanielSon

Reputation: 1545

How to compare Python two list of lists and remove duplicates by a single element in lists

If you have two list of lists, and you would like to remove lists from one list of lists, that have a matching element for lists in the other list of lists, how do you achieve this?

Say you have

a = [[a,b,c],[d,e,f]]
b = [[g,h,i],[k,l,m],[n,o,c]]

How do you check the 3rd element in each list in b against the 3rd element in each list in a, and if there is a match then remove the list containing that match from b.

The desired end result here is

b = [[g,h,i],[k,l,m]]

because "c" is the 3rd element in one of the lists from a, and also is the 3rd element in one of the lists from b, so that list in b is removed.

I've tried

c = [x for x in b for y in a if not x[2] == y[2]]
c = [y for x,y in zip(a,b) if not x[2] == y[2]]
c = [[x for x in b if not x[2] == y[2]] for y in a]

so far, with all failing.

I've researched online and on SOF, and although there might be an answer for this, I've not been able to find one which deals with this specifically.

Upvotes: 1

Views: 782

Answers (1)

Rakesh
Rakesh

Reputation: 82765

This might help.

a = [["a","b","c"],["d","e","f"]] 
b = [["g","h","i"],["k","l","m"],["n","o","c"]]

check = [i[2] for i in a]
print([i for i in b if i[2] not in check])

Output:

[['g', 'h', 'i'], ['k', 'l', 'm']]

Upvotes: 4

Related Questions