[英]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.