Sorting a list with entries of unequal types

Peter Otten __peter__ at web.de
Fri Jan 29 09:59:03 CET 2010


Ben Finney wrote:

> Peter Otten <__peter__ at web.de> writes:
> 
>> 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}
> 
> The problem with this approach is that it assumes I know all the types
> of elements that will be sorted; I don't. I want to sort a list coming
> from some other part of the code, and I don't want to arbitrarily limit
> the types of the list elements.

I don't see the limitation here. The above key functions sorts unknown types 
by name, then id(type) then instance.

Peter



More information about the Python-list mailing list