如果我有这个列表:

[[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's评论建议使用以下方法来提高行为效率:
next(i for i,v in enumerate(l) if 12 in v)

10-07 19:04
查看更多