Find min value in array > 0

前端 未结 7 1952
夕颜
夕颜 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:11

    You can use the min function and enumerate function, like this

    result = min(enumerate(a), key=lambda x: x[1] if x[1] > 0 else float('inf'))
    print("Position : {}, Value : {}".format(*result)
    # Position : 3, Value : 1
    

    This makes sure that, if the value is greater than 0, then use that value for the minimum value comparison otherwise use the maximum possible value (float('inf')).

    Since we iterate along with the actual index of the items, we don't have to find the actual index with another loop.

提交回复
热议问题