Python: sort function breaks in the presence of nan

前端 未结 6 1981
隐瞒了意图╮
隐瞒了意图╮ 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 08:01

    I'm not sure about the bug, but the workaround may be the following:

    sorted(
        (2, 1, float('nan')),
        lambda x,y: x is float('nan') and -1 
                    or (y is float('nan') and 1
                    or cmp(x,y)))
    

    which results in:

    ('nan', 1, 2)
    

    Or remove nans before sorting or anything else.

提交回复
热议问题