Sarma Tangirala wrote:

> I was banging my head about a pythonic way of doing the following,
> 
> 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.

Python's list.sort() is "stable", it doesn't change the order of items that 
compare equal. Therefore you can achieve your goal by sorting twice:

>>> items = [[1,2], [2, 2], [3, 2], [0, 0]]
>>> items.sort(key=itemgetter(0), reverse=True)
>>> items
[[3, 2], [2, 2], [1, 2], [0, 0]]
>>> items.sort(key=itemgetter(1))
>>> items
[[0, 0], [3, 2], [2, 2], [1, 2]]

(I changed your last item to [0, 0] to allow me to demonstrate that two 
sorts are indeed necessary)

Using a more complex key is also possible,

>>> sorted([[1,2], [2, 2], [3, 2], [0, 0]], key=lambda item: (item[1], -
item[0]))
[[0, 0], [3, 2], [2, 2], [1, 2]]

but I think that is less elegant.

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

Reply via email to