Sorting a list with entries of unequal types

Peter Otten __peter__ at web.de
Fri Jan 29 01:35:52 CET 2010


Ben Finney wrote:

> Python 2.6 tells me that, in Python 3, sorting a list with entries of
> incompatible types is not allowed:

> $ python2.6 -3 -c "foo = [1, True, 'green', 4, -27, 15.3]; foo.sort();
> print foo;" -c:1: DeprecationWarning: comparing unequal types not
> supported in 3.x
> [-27, 1, True, 4, 15.300000000000001, 'green']
> =====
> 
> So how should I be sorting a list with entries of “unequal types” such
> that it will work in Python 3?
 
I can't find the relevant part of the 2.6 documentation, but something like

>>> def key(x):
...     t = type(x)
...     t = compat.get(t, t)
...     return t.__name__, id(t), x
...
>>> compat = {bool: float, int: float}
>>> sorted([1, True, 'green', 4, -27, 15.3], key=key)
[-27, 1, True, 4, 15.300000000000001, 'green']

should work.

Peter



More information about the Python-list mailing list