问题
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 the 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)]
回答1:
You could also try this:
min(filter(lambda t: not math.isnan(t[1]), l), key=itemgetter(1))
where itemgetter
refers to operator.itemgetter.
回答2:
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])
回答3:
>>> 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 don't think nan is considered smaller than regular floats. Probably min is comparing the strings alphabetically.
(Not a complete answer, but might help)
回答4:
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
Fails on the empty list, but otherwise solves the problem.
来源:https://stackoverflow.com/questions/15148684/list-of-tuples-string-floatwith-nan-how-to-get-the-min-value