[Tutor] Debugging a sort error.

mhysnm1964 at gmail.com mhysnm1964 at gmail.com
Sun Jan 13 17:32:28 EST 2019


Peter,

Thanks for the code for a custom key. That will come in handy later down the
track.

-----Original Message-----
From: Tutor <tutor-bounces+mhysnm1964=gmail.com at python.org> On Behalf Of
Peter Otten
Sent: Sunday, 13 January 2019 10:00 PM
To: tutor at python.org
Subject: Re: [Tutor] Debugging a sort error.

mhysnm1964 at gmail.com wrote:

> Issue, following error is generated after trying to sort a list of 
> strings.
> 
> description.sort()
> TypeError: unorderable types: float() < str()

Consider

>>> descriptions = ["foo", "bar", 123, 3.14, 42, 200.1, "0"]
>>> sorted(descriptions)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()

If there are only numbers and strings in the list you can force the sort to
succeed with the following custom key function:

>>> def key(item):
...     return isinstance(item, str), item
... 

This will move the numbers to the beginning of the list:

>>> sorted(descriptions, key=key)
[3.14, 42, 123, 200.1, '0', 'bar', 'foo']


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list