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

Deadly 提交于 2021-01-27 06:45:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!