简体   繁体   English

获取包含值的第一个子列表的索引的最快方法

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

I have a list of lists in python of the form 我在python表单中有一个列表列表

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) . 这样,通过键O(1)可以立即进行查找。 Let's use defaultdict(list) : 让我们使用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: 使用带有生成器表达式的next()非常简单:

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. 这样做的问题是,如果不出现value ,它将有一个错误。 With a slightly longer function call, you can make a default of -1: 使用稍长的函数调用,您可以将默认设置为-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 这是使用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. 以下是python中的简单代码,用于在列表列表中查找元素。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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