List of tuples (string, float) with NaN. How to get the min value?

I have a list of List of Tuples (string, float) with float('nan') . How can I get the tuple with the smallest number? If I use min, I always get nan .

 [('GroundBasedMechWT', nan), ('GroundBasedCTL', nan), ('GroundBasedManualWT', nan), ('GroundBasedManualLog', nan), ('CableManualWTLog', 60.77), ('CableManualWT', 58.52), ('CableManualLog', 68.17), ('CableManualCTL', nan), ('HelicopterManualWT', 96.82), ('HelicopterManualCTL', nan)] 
+4
source share
4 answers

You can also try the following:

 min(filter(lambda t: not math.isnan(t[1]), l), key=itemgetter(1)) 

where itemgetter refers to operator.itemgetter .

+1
source

You can use a custom key that will return a very high value for NaN :

 min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1]) 
+2
source
 >>> nan=float('NaN') >>> x=[('GroundBasedMechWT', nan), ('GroundBasedCTL', nan), ('GroundBasedManualWT', nan), ('GroundBasedManualLog', nan), ('CableManualWTLog', 60.77), ('CableManualWT', 58.52), ('CableManualLog', 68.17), ('CableManualCTL', nan), ('HelicopterManualWT', 96.82), ('HelicopterManualCTL', nan)] >>> nan<1 False >>> nan<1.0 False >>> min(x) ('CableManualCTL', nan) 

I do not think nan is considered smaller than regular floats. Probably min compares strings in alphabetical order.

(Not a complete answer, but may help)

0
source
 nan=float('NaN') x=[('GroundBasedMechWT', nan), ('GroundBasedCTL', nan), ('GroundBasedManualWT', nan), ('GroundBasedManualLog', nan), ('CableManualWTLog', 60.77), ('CableManualWT', 58.52), ('CableManualLog', 68.17), ('CableManualCTL', nan), ('HelicopterManualWT', 96.82), ('HelicopterManualCTL', nan)] val=('foo', float('Inf')) #thanks for teaching me that for tup in x: if tup[1]<val[1]: val=tup print val 

Failure in an empty list, but otherwise solves the problem.

0
source

All Articles