Python 获取包含值的第一个子列表的索引的最快方法
我有一个python格式的列表Python 获取包含值的第一个子列表的索引的最快方法,python,list,multidimensional-array,Python,List,Multidimensional Array,我有一个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
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)
可以立即进行查找。让我们使用:
使用带有生成器表达式的
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))
谢谢大家,我最终用字典达到了我的最终目标
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))