Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare a list of lists with another list, and return common one

Let´s say I have the following list of lists:

list1 = [[A,B],[C,D],[E, F]]
list2 = [A, B, F]

I want a function to return the common list with respect to the first one. The expecting result of this example would be:

result = [[A,B],[],[F]]

I already tried to iterate over each element of list1, and by comparing with list2, create a new array appending each element. I know how to iterate over the list of lists, but I do not find the way to create a list of lists for "result".

The lists aren't large, about 5 elements. There is a possibility that the items can be repeated, but the order within the lists, inside the whole list, is not important.

like image 213
edualvarado Avatar asked Dec 13 '22 15:12

edualvarado


2 Answers

With set arithmetic, extremely easy and fast:

set2 = set(list2)
[list(set(e) & set2) for e in list1]

If the lists can contain non-unique items, then... let's use counters!

from collections import Counter
counter2 = Counter(list2)
[list((Counter(e) & counter2).elements()) for e in list1]
like image 150
Amadan Avatar answered May 17 '23 08:05

Amadan


This is one approach. Using list comprehension

Ex:

list1 = [["A","B"],["C","D"],["E", "F"]]
list2 = ["A", "B", "F"]

result = [[j for j in i if j in list2] for i in list1]
print(result)

Output:

[['A', 'B'], [], ['F']]
like image 31
Rakesh Avatar answered May 17 '23 08:05

Rakesh