在列表列表中查找项目的索引

Pea*_*ser 5 python indexing integer list

如果我有这个列表:

[[1,2,3,4],[5,6,7,8,9,10],[11,12,13]]
Run Code Online (Sandbox Code Playgroud)

我怎样才能根据给定的值找到子列表本身的索引?

例如:

如果我的值为 2,则返回的索引将为 0

如果我的值为 9,则返回的索引将为 1

如果我的值为 11,则索引为 2

jrd*_*rd1 9

只需使用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] 
Run Code Online (Sandbox Code Playgroud)

这输出:

[2]
Run Code Online (Sandbox Code Playgroud)

编辑:

@hlt 的评论建议使用以下更有效的行为:

next(i for i,v in enumerate(l) if 12 in v)
Run Code Online (Sandbox Code Playgroud)

  • 这将查找所有事件。您需要使用 `[0]` 或(更有效)将事物转换为迭代器,然后使用 `next` 提取第一个元素(即 `next(i for i,v in enumerate(l) if 12 in v) `) (2认同)