First Python list index greater than x?

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

    I know there are already plenty of answers, but I sometimes I feel that the word pythonic is translated into 'one-liner'.

    When I think a better definition is closer to this answer:

    "Exploiting the features of the Python language to produce code that is clear, concise and maintainable."

    While some of the above answers are concise, I do not find them to be clear and it would take a newbie programmer a while to understand, therefore not making them extremely maintainable for a team built of many skill levels.

    l = [0.5, 0.3, 0.9, 0.8]
    
    def f(l, x):
        for i in l:
            if i >x: break
        return l.index(i)
    
    
    f(l,.7)
    

    or

    l = [0.5, 0.3, 0.9, 0.8]
    
    def f(l, x):
        for i in l:
            if i >x: return l.index(i)
    
    
    
    f(l,.7)
    

    I think the above is easily understood by a newbie and is still concise enough to be accepted by any veteran python programmer.

    I think writing dumb code is a positive.

提交回复
热议问题