Fastest way to check if a value exists in a list

后端 未结 12 2325
猫巷女王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:40

    You could put your items into a set. Set lookups are very efficient.

    Try:

    s = set(a)
    if 7 in s:
      # do stuff
    

    edit In a comment you say that you'd like to get the index of the element. Unfortunately, sets have no notion of element position. An alternative is to pre-sort your list and then use binary search every time you need to find an element.

提交回复
热议问题