简体   繁体   中英

Fastest way to get the index of the first sublist that contains value

I have a list of lists in python of the form

A=[[1,2,3,4],
   [5,6,7,8],
   [9,10,11,12]]

I need to get a fast way to get the row index of an element in that structure.

method(2) = 0

method(8) = 1

method(12) = 2

and so on. As always, the fastest the method the better, as my actual list of lists is quite large.

In this state, the data structure (list of lists) is not quite convenient and efficient for the queries you want to make on it . Restructure it to have it in a form:

item -> list of sublist indexes  # assuming items can be present in multiple sublists

This way the lookups would be instant, by key - O(1) . Let's use defaultdict(list) :

>>> from collections import defaultdict
>>>
>>> d = defaultdict(list)
>>> for index, sublist in enumerate(A):
...     for item in sublist:
...         d[item].append(index)
... 
>>> d[2]
[0]
>>> d[8]
[1]
>>> d[12]
[2]

It is very simple using next() with a generator expression:

def method(lists, value):
    return next(i for i, v in enumerate(lists) if value in v)

The problem with that is that it will have an error if value does not occur. With a slightly longer function call, you can make a default of -1:

def method(lists, value):
    return next((i for i,v in enumerate(lists) if value in v), -1)

Here is another way using numpy

import numpy

A = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]

my_array = numpy.array(A)

numpy.where(my_array==2) ## will return both the list and the index within the list
numpy.where(my_array==12)

## As a follow up if we want only the index we can always do :
numpy.where(my_array==12)[0][0] # will return 2 , index of list
numpy.where(my_array==12)[1][0] # will return 3 , index within list

find operation in list is linear. Following is simple code in python to find an element in list of lists.

A=[[1,2,3,4],
   [5,6,7,8],
   [9,10,11,12]]

def method(value):
    for idx, list in enumerate(A):
        if value in list:
            return idx
    return -1

print (method(12))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM