[英]Finding the index of an item in a list of lists
If I have this list of lists: 如果我有这个列表列表:
[[1,2,3,4],[5,6,7,8,9,10],[11,12,13]]
How might I be able to find the index of the sublist itself according to the value given? 我怎样才能根据给定的值找到子列表本身的索引?
For example: 例如:
If my value is 2, The index returned would be 0 如果我的值为2,则返回的索引将为0
If my value is 9, the index returned would be 1 如果我的值为9,则返回的索引将为1
if my value is 11, the index would be 2 如果我的值为11,则索引为2
Just use enumerate
: 只需使用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]
This outputs: 这输出:
[2]
Edit: 编辑:
@hlt's comment suggests using the following for more efficient behavior: @hlt的评论建议使用以下更有效的行为:
next(i for i,v in enumerate(l) if 12 in v)
Either use a list-comp as demonstrated by @jrd1 if you want all indices, or if you want just the first occurrence, then: 如果您想要所有索引,或者如果您只想要第一次出现,请使用@ jrd1演示的list-comp,然后:
next((idx for idx, val in enumerate(your_list) if 2 in val), None)
We use None
here as a default value instead of raising a StopIteration
where the value is not found in any sublist. 我们在这里使用None
作为默认值,而不是在任何子列表中找不到值的StopIteration
。 Remove the default value if you wish the exception raised instead. 如果您希望引发异常,请删除默认值。
If you have many queries and/or a dynamic list of lists, then you are better off making a map. 如果您有许多查询和/或动态列表列表,那么最好制作一张地图。 Specifically a value:set map. 特别是一个值:设置地图。 Where you map the value to a set of indices (sub-lists) that contain that value. 将值映射到包含该值的一组索引(子列表)的位置。 Though this works best if the list doesn't change. 虽然如果列表没有改变,这种方法效果最好。
Example for [[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]
: 例如[[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}
}
You can also treat the sub-lists as intervals (covering a range of indices) and allowing for O(log N) look up and O(log N) add/remove sublist/element by building an interval tree . 您还可以将子列表视为间隔(覆盖一系列索引)并允许O(log N)查找和O(log N)通过构建间隔树来添加/删除子列表/元素。 It takes O(L log L) to build the interval tree where L is the number of sublists. 它需要O(L log L)来构建区间树,其中L是子列表的数量。
Here's an (albeit somewhat inefficient, yet concise) recursive solution: 这是一个(虽然效率低,但简洁)递归解决方案:
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.