繁体   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