Python: sort function breaks in the presence of nan

前端 未结 6 1985
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 07:34

sorted([2, float(\'nan\'), 1]) returns [2, nan, 1]

(At least on Activestate Python 3.1 implementation.)

I understand nan

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 07:42

    Assuming you want to keep the NaNs and order them as the lowest "values", here is a workaround working both with non-unique nan, unique numpy nan, numerical and non numerical objects:

    def is_nan(x):
        return (x is np.nan or x != x)
    
    list_ = [2, float('nan'), 'z', 1, 'a', np.nan, 4, float('nan')]
    sorted(list_, key = lambda x : float('-inf') if is_nan(x) else x)
    # [nan, nan, nan, 1, 2, 4, 'a', 'z']
    

提交回复
热议问题