Fastest way to check if a value exists in a list

后端 未结 12 2244
猫巷女王i
猫巷女王i 2020-11-22 00:18

What is the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is?

I know that all values in the list are uniqu

12条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 00:42

    Because the question is not always supposed to be understood as the fastest technical way - I always suggest the most straightforward fastest way to understand/write: a list comprehension, one-liner

    [i for i in list_from_which_to_search if i in list_to_search_in]
    

    I had a list_to_search_in with all the items, and wanted to return the indexes of the items in the list_from_which_to_search.

    This returns the indexes in a nice list.

    There are other ways to check this problem - however list comprehensions are quick enough, adding to the fact of writing it quick enough, to solve a problem.

提交回复
热议问题