[Tutor] Sorting Nested Lists

Walter Prins wprins at gmail.com
Mon Jan 9 14:18:36 CET 2012


Hi,

On 9 January 2012 12:31, Sarma Tangirala <tvssarma.omega9 at gmail.com> wrote:
> Given a nested list, how do I sort the uppermost list based on one key and
> when a special condition occurs a sort on another key should be performed?
>
> For example, [[1,2], [2, 2], [3, 2], [4, 0]] would be sorted, in my example
> as, [[4, 0], [3, 2], [2, 2], [1, 2]]. That is, sort on the second value and
> in case they are equal, reverse sort on the first value.
>
> I tried doing this using sorted and using a custom cmp function but not sure
> about how to define the cmp function.

See the following page (particularly the section that describes
"multiple levels of sorting") for how to do (I think) what you want
(though this does not use the compare function):
http://wiki.python.org/moin/HowTo/Sorting

If you really want to have this done via the compare function method
then post back again.

Walter


More information about the Tutor mailing list