First Python list index greater than x?

后端 未结 12 1883
遇见更好的自我
遇见更好的自我 2020-12-02 08:27

What would be the most Pythonic way to find the first index in a list that is greater than x?

For example, with

list = [0.5, 0.3, 0.9, 0.8]


        
相关标签:
12条回答
  • 2020-12-02 09:06
    for index, elem in enumerate(elements):
        if elem > reference:
            return index
    raise ValueError("Nothing Found")
    
    0 讨论(0)
  • 2020-12-02 09:14

    Try this one:

    def Renumerate(l):
        return [(len(l) - x, y) for x,y in enumerate(l)]
    

    example code:

    Renumerate(range(10))
    

    output:

    (10, 0)
    (9, 1)
    (8, 2)
    (7, 3)
    (6, 4)
    (5, 5)
    (4, 6)
    (3, 7)
    (2, 8)
    (1, 9)
    
    0 讨论(0)
  • 2020-12-02 09:17
    >>> alist= [0.5, 0.3, 0.9, 0.8]
    >>> [ n for n,i in enumerate(alist) if i>0.7 ][0]
    2
    
    0 讨论(0)
  • 2020-12-02 09:18

    You could also do this using numpy:

    import numpy as np
    
    list(np.array(SearchList) > x).index(True)
    
    0 讨论(0)
  • 2020-12-02 09:23

    1) NUMPY SOLUTION, general lists

    If you are happy to use numpy, then the following will work on general lists (sorted or unsorted):

    numpy.argwhere(np.array(searchlist)>x)[0]
    

    or if you need the answer as a list:

    numpy.argwhere(np.array(searchlist)>x).tolist()[0]
    

    or if you need the answer as a integer index:

    numpy.argwhere(np.array(searchlist)>x).tolist()[0][0]
    

    2) NUMPY SOLUTION, sorted lists

    However, if your search list is sorted, it is much cleaner and nicer to use the function np.searchsorted:

    numpy.searchsorted(searchlist,x)
    

    The nice thing about using this function is that as well as search for a single value x, you can also return a list of indices for a list of values x, (and it is very efficient relative to a list comprehension in this case).

    0 讨论(0)
  • 2020-12-02 09:25

    Another one:

    map(lambda x: x>.7, seq).index(True)
    
    0 讨论(0)
提交回复
热议问题