Finding the index of an item in a list

后端 未结 30 3273
你的背包
你的背包 2020-11-21 05:28

Given a list [\"foo\", \"bar\", \"baz\"] and an item in the list \"bar\", how do I get its index (1) in Python?

30条回答
  •  迷失自我
    2020-11-21 05:52

    If you are going to find an index once then using "index" method is fine. However, if you are going to search your data more than once then I recommend using bisect module. Keep in mind that using bisect module data must be sorted. So you sort data once and then you can use bisect. Using bisect module on my machine is about 20 times faster than using index method.

    Here is an example of code using Python 3.8 and above syntax:

    import bisect
    from timeit import timeit
    
    def bisect_search(container, value):
        return (
          index 
          if (index := bisect.bisect_left(container, value)) < len(container) 
          and container[index] == value else -1
        )
    
    data = list(range(1000))
    # value to search
    value = 666
    
    # times to test
    ttt = 1000
    
    t1 = timeit(lambda: data.index(value), number=ttt)
    t2 = timeit(lambda: bisect_search(data, value), number=ttt)
    
    print(f"{t1=:.4f}, {t2=:.4f}, diffs {t1/t2=:.2f}")
    

    Output:

    t1=0.0400, t2=0.0020, diffs t1/t2=19.60
    

提交回复
热议问题