Find min value in array > 0

前端 未结 7 1956
夕颜
夕颜 2021-02-07 05:49

I am looking to find the lowest positive value in an array and its position in the list. If a value within the list is duplicated, only the FIRST instance is of interest. This i

7条回答
  •  深忆病人
    2021-02-07 06:17

    Here is another way of doing it with a generator expression. Note how the values coming from enumerate (a and b) are swapped in the tuple to sort correctly.

    value,position = min(((b,a) for a,b in enumerate(myArray) if b>0), default=(None,None))
    

    The default argument will be returned when the generator expression returns nothing (i.e. there are no items greater than 0). The default can be set to whatever makes sense in the surrounding program logic - here returning None will allow you to test with either if value: or if position:

提交回复
热议问题