Skip to content
Advertisement

Checking if list element in list of lists and returning sublist

I have two lists

JavaScript

and want to return those sublistst of list2 that contain elements of list1. So far I tried using any:

JavaScript

and a naive approach

JavaScript

But I only managed to repeat empty list. The result should be

JavaScript

Not sure, where I’m going wrong. Is there maybe a way using list comprehensions or mixing list comprehensions and ‘any’ function?

Advertisement

Answer

What you have looks correct and works for me locally too:

JavaScript

It returns [['2', 'B'], ['3', 'D'], ['5', 'C']] which is the expected result right?

Also note that you can speed up your implementation by changing list1 into a set list1 = set(['B', 'C', 'D']) and changing the if condition to if any (item in list1 for item in l2):.
This is because item in list1 is much faster if list1 is a set than a list. That’s because set uses a hashmap under the hood the quickly accesss elements.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement