Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Intersection of two lists of lists [duplicate]

These are my two lists;

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,9]]
kDash = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,6], [1,2]]

My output should be the following;

[[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]

how can I get to this output?

thank you in advance

like image 550
Nimmi Rashinika Avatar asked Jan 30 '16 11:01

Nimmi Rashinika


1 Answers

You will have to convert the lists to list of tuples, and then use the intersection. Note that below solution may have elements in a different order, and duplicates will obviously not be there, since I'm using set.

In [1]: l1 = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,9]]

In [2]: l2 = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,6], [1,2]]

In [3]: [list(x) for x in set(tuple(x) for x in l1).intersection(set(tuple(x) for x in l2))]
Out[3]: [[1, 2], [5, 6, 2], [3], [4]]

You can alternatively save the intersection in a variable and get the final list, if order, duplicates are necessary:

In [4]: intersection = set(tuple(x) for x in l1).intersection(set(tuple(x) for x in l2))

In [5]: [x for x in l1 if tuple(x) in intersection]
Out[5]: [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]

And the intersection, just in case if you are interested.

In [6]: print intersection
set([(1, 2), (5, 6, 2), (3,), (4,)])

This will work pretty well for large lists, but if the lists are small, do explore the other solution by @timegb (whose solution will be highly unoptimal for longer lists)

like image 132
Anshul Goyal Avatar answered Oct 03 '22 07:10

Anshul Goyal