繁体   English   中英

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

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

我在python表单中有一个列表列表

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

我需要一种快速的方法来获取该结构中元素的行索引。

method(2) = 0

method(8) = 1

method(12) = 2

等等。 与往常一样,最快的方法越好,因为我的实际列表很大。

在这种状态下, 数据结构(列表列表)对于要在其上进行的查询而言并不十分方便和有效 对其进行重组以使其具有以下形式:

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

这样,通过键O(1)可以立即进行查找。 让我们使用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]

使用带有生成器表达式的next()非常简单:

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

这样做的问题是,如果不出现value ,它将有一个错误。 使用稍长的函数调用,您可以将默认设置为-1:

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

这是使用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

在列表中查找操作是线性的。 以下是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