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.
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]
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With