Zero
Zero

Reputation: 76927

Difference between list of lists

I have two lists

A=[['1','1'],['2','1'],['3','2']]

B=[['1','1'],['2','2']]

I want to perform A-B operation on these comparing only first element.

so A-B should give

Output=[['3', '2']]

So far, I could do only on row comparison

[x for x in A if not x in B]

which gives output as [['2', '1'], ['3', '2']]

Upvotes: 0

Views: 2199

Answers (3)

thiruvenkadam
thiruvenkadam

Reputation: 4250

I could think of a different list comprehension

A=[['1','1'],['2','1'],['3','2']]
B=[['1','1'],['2','2']]
b = dict(B)
output_list = [item for item in A if item[0] not in b]

This is order preserving as well and can work even if there are duplicate fist elements in the inner list of A. Also it can be extended to check for exact pair if needed like this:

A=[['1','1'],['2','1'],['3','2']]
B=[['1','1'],['2','2']]
b = dict(B)
output_list = [item for item in A if item[0] not in b or b[item[0]] != item[1]]

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

You can also use collections.OrderedDict and set difference here:

>>> from collections import OrderedDict
>>> dic1 = OrderedDict((k[0],k) for k in A)
>>> [dic1[x] for x in set(dic1) - set(y[0] for y in B)]
[['3', '2']]

Overall complexity is going to be O(max(len(A), len(B)))

If order doesn't matter then a normal dict is sufficient.

Upvotes: 0

TerryA
TerryA

Reputation: 59974

This?

>>> [i for i in A if not any(i[0] == k for k, _ in B)]
[['3', '2']]

any() is used to check if the first element of each list is the same as any other value in every list in B. If it is, it returns True, but as we want the opposite of this, we use not any(...)

Upvotes: 1

Related Questions