ggnoredo
ggnoredo

Reputation: 821

Python search multiple values exists in list of lists

I want to give an example directly to explain better

search1 = 'test'
search2 = 'value'

search_array = [[], [], [], [], ....]

I have a list of lists with different lengths and values. I want to find index number of a list if both search1 and search2 exists. At the moment i'm doing nested loops which is super slow performance wise with 50.000 items in list.

Upvotes: 1

Views: 323

Answers (1)

Mykola Semenov
Mykola Semenov

Reputation: 802

If you can change data structure, you could use list of sets, so time complexity of search becomes O(N) instead of O(N * M):

search1 = 'test'
search2 = 'value'

search_array = [set(), set(), set(), set(), ....]

And to find indices you need in operator and one loop:

indices = [i for (i, s) in enumerate(search_array) if search1 in s and search2 in s]

Upvotes: 1

Related Questions