sort the list

Giovanni Bajo raNOsky at deveSPAMler.com
Mon Nov 21 09:53:18 EST 2005


Fredrik Lundh wrote:

>> I have a list like [[1,4],[3,9],[2,5],[3,2]]. How can I sort the list
>> based on the second value in the item?
>> That is,
>> I want the list to be:
>> [[3,2],[1,4],[2,5],[3,9]]
>
> since you seem to be using 2.3, the solution is to use a custom
> compare function:
>
>     >>> L = [[1,4],[3,9],[2,5],[3,2]]
>     >>> def mycmp(a, b):
>     ...     return cmp(a[1], b[1])
>     ...
>     >>> L.sort(mycmp)
>     >>> L
>     [[3, 2], [1, 4], [2, 5], [3, 9]]
>
> under 2.4, you can use the key argument together with the item-
> getter function to sort on a given column; look for "itemgetter" on
> this page for some examples:
>
>     http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305304

To clarify, itemgetter is just an optimization. Even without it, you can
still use "key":

>>> L = [[1,4],[3,9],[2,5],[3,2]]
>>> def mykey(e):
...     return e[1]
...
>>> L.sort(key=mykey)
>>> L
[[3, 2], [1, 4], [2, 5], [3, 9]]

Using the "key" keyword argument can be easier to understand ("sorting
against the second element" == "second element is the key").
-- 
Giovanni Bajo





More information about the Python-list mailing list