First Python list index greater than x?

后端 未结 12 1936
遇见更好的自我
遇见更好的自我 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:02

    I had similar problem when my list was very long. comprehension or filter -based solutions would go thru whole list. itertools.takewhile will break the loop once condition become false first time:

    from itertools import takewhile
    
    def f(l, b): return len([x for x in takewhile(lambda x: x[1] <= b, enumerate(l))])
    
    l = [0.5, 0.3, 0.9, 0.8]
    f(l, 0.7)
    

提交回复
热议问题