簡體   English   中英

查找列表列表中項目的索引

[英]Finding the index of an item in a list of lists

如果我有這個列表列表:

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

我怎樣才能根據給定的值找到子列表本身的索引?

例如:

如果我的值為2,則返回的索引將為0

如果我的值為9,則返回的索引將為1

如果我的值為11,則索引為2

只需使用enumerate

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

# e.g.: find the index of the list containing 12
# This returns the first match (i.e. using index 0), if you want all matches
# simply remove the `[0]`
print [i for i, lst in enumerate(l) if 12 in lst][0] 

這輸出:

[2]

編輯:

@hlt的評論建議使用以下更有效的行為:

next(i for i,v in enumerate(l) if 12 in v)

如果您想要所有索引,或者如果您只想要第一次出現,請使用@ jrd1演示的list-comp,然后:

next((idx for idx, val in enumerate(your_list) if 2 in val), None)

我們在這里使用None作為默認值,而不是在任何子列表中找不到值的StopIteration 如果您希望引發異常,請刪除默認值。

如果您有許多查詢和/或動態列表列表,那么最好制作一張地圖。 特別是一個值:設置地圖。 將值映射到包含該值的一組索引(子列表)的位置。 雖然如果列表沒有改變,這種方法效果最好。

例如[[1,2,3,4],[5,6,7,8,9,10], [11,12,13], [1,2,3,4,5,6,7,8,9,10,11,12,13]

# Code for populating the map
map = collections.defaultdict(set)
index = 0
for i,v in enumerate(l):
    for _ in v:
        map[index].add(i)
        index += 1

# Result:
map = {
    1: {0,3},
    2: {0,3},
    3: {0,3},
    4: {0,3},
    5: {1,3},
    6: {1,3},
    7: {1,3},
    8: {1,3},
    9: {1,3},
    10:{1,3},
    11:{2,3},
    12:{2,3},
    13:{2,3}
}

您還可以將子列表視為間隔(覆蓋一系列索引)並允許O(log N)查找和O(log N)通過構建間隔樹來添加/刪除子列表/元素。 它需要O(L log L)來構建區間樹,其中L是子列表的數量。

這是一個(雖然效率低,但簡潔)遞歸解決方案:

def get_index(lst, num, index=0):
    if num in lst[index]:
        return index
    else:
        return get_index(lst, num, index + 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM