Python - Intersection of Two List Lists

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 conclusion should be as follows:

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

How can I get to this exit?

early

+5
source share
4 answers

You will need to convert the lists to a list of tuples, and then use the intersection. Note that the solution below may have the elements in a different order, and there will obviously not be duplicates, since I am 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 also save the intersection in a variable and get the final list, if order is needed, duplicates:

 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 you are interested.

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

This will work well for large lists, but if the lists are small, check out another @timegb solution (which will be very suboptimal for longer lists)

+4
source

Since your output list has duplicate elements, it really doesn't seem to you that you need a classic intersection. A basic understanding of the list will do everything.

 >>> 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]] >>> [x for x in k if x in kDash] [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]] 

For large lists, we want to get the time needed to call __contains__ in O (1) instead of O (n):

 >>> stuff_in_kDash = set(map(tuple, kDash)) >>> [x for x in k if tuple(x) in stuff_in_kDash] [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]] 
+3
source

A cleaner way to record the intersection is

 {tuple(x) for x in l1} & {tuple(x) for x in l2} 

A good alternative is

 {tuple(x) for x in l1}.intersection(map(tuple, l2)) 
+2
source

Despite the fact that much more elegant solutions were written here, here is another

 def foo(L1,L2): res=[] for lst in L1: if lst in L2: res.append(lst) return res 
0
source

Source: https://habr.com/ru/post/1241880/


All Articles