如何找到包含所需值的列表(在列表中)的第一个实例的索引(在Python中)?

时间:2016-12-07 15:01:51

标签: python

我有一个类似于以下内容的元组列表

list_of_list = [(0,1,2), (0,1), (0,1,3,4), (0,1,2,3,4)]

我想第一次找到具有特定整数的索引。例如,我想找到第一次存在3,并希望它返回索引2.我还希望它返回None如果它找不到任何东西。我目前有以下代码

def find_index_of_solution(list_of_list, value_I_am_searching_for):
  for idx, list_item in enumerate(list_of_list):
    if value_I_am_searching_for in list_item:
      return idx
  return None

有更好的方法吗?谢谢!

2 个答案:

答案 0 :(得分:1)

try:
    return next(index for index, lst in enumerate(list_of_list) if my_value in lst)
except StopIteration:
    return None

在括号内,是一个生成器表达式。 next返回第一个元素。 enumerate用于迭代迭代的索引和值。最后,使用异常比检查python更受欢迎,无论是样式还是性能

答案 1 :(得分:1)

你的:

%%timeit
list_of_list = [(0,1,2), (0,1), (0,1,3,4), (0,1,2,3,4)]


def findIdx(list_of_list, value_I_am_searching_for):
    for idx, list_item in enumerate(list_of_list):
        if value_I_am_searching_for in list_item:
          return idx
    return None


findIdx(list_of_list, 3)


1000000 loops, best of 3: 1.18 µs per loop

Blue_note's:

%%timeit
list_of_list = [(0,1,2), (0,1), (0,1,3,4), (0,1,2,3,4)]
my_value = 3
try:
    return next(index for index, lst in enumerate(list_of_list) if my_value in lst)
except StopIteration:
    return None

1 loop, best of 3: 2 s per loop

另一个:

%%timeit
list_of_list = [(0,1,2), (0,1), (0,1,3,4), (0,1,2,3,4)]


def findIdx(lst, i):
    return [l.index(i) if i in l else 'None' for l in lst ]


findIdx(list_of_list, 3)

100000 loops, best of 3: 2 µs per loop

我的意见,坚持你现在拥有的东西..

编辑: 我错过了这个......

  

例如,我想找到第一次存在3,并希望它   返回索引2.

NVM。