How can I get 2.x-like sorting behaviour in Python 3.x?

后端 未结 10 847
陌清茗
陌清茗 2020-11-27 06:50

I\'m trying to replicate (and if possible improve on) Python 2.x\'s sorting behaviour in 3.x, so that mutually orderable types like int, float etc.

10条回答
  •  执笔经年
    2020-11-27 07:30

    Not running Python 3 here, but maybe something like this would work. Test to see if doing a "less than" compare on "value" creates an exception and then do "something" to handle that case, like convert it to a string.

    Of course you'd still need more special handling if there are other types in your list that are not the same type but are mutually orderable.

    from numbers import Real
    from decimal import Decimal
    
    def motley(value):
        numeric = Real, Decimal
        if isinstance(value, numeric):
            typeinfo = numeric
        else:
            typeinfo = type(value)
    
        try:
            x = value < value
        except TypeError:
            value = repr(value)
    
        return repr(typeinfo), value
    
    >>> print sorted([0, 'one', 2.3, 'four', -5, (2+3j), (1-3j)], key=motley)
    [-5, 0, 2.3, (1-3j), (2+3j), 'four', 'one']
    

提交回复
热议问题