Finding the indices of matching elements in list in Python

前端 未结 3 856
北荒
北荒 2020-11-30 00:09

I have a long list of float numbers ranging from 1 to 5, called \"average\", and I want to return the list of indices for elements that are smaller than a or larger than b

3条回答
  •  無奈伤痛
    2020-11-30 00:31

    if you're doing a lot of this kind of thing you should consider using numpy.

    In [56]: import random, numpy
    
    In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list
    
    In [58]: a, b = 1, 3
    
    In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
    Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])
    

    In response to Seanny123's question, I used this timing code:

    import numpy, timeit, random
    
    a, b = 1, 3
    
    lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])
    
    def numpy_way():
        numpy.flatnonzero((lst > 1) & (lst < 3))[:10]
    
    def list_comprehension():
        [e for e in lst if 1 < e < 3][:10]
    
    print timeit.timeit(numpy_way)
    print timeit.timeit(list_comprehension)
    

    The numpy version is over 60 times faster.

提交回复
热议问题