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
只需使用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)