Sorting an array on the nth element in a list

Vlastimil Brom vlastimil.brom at gmail.com
Wed Aug 20 15:21:16 EDT 2008


2008/8/20 Ron Brennan <brennan.ron at gmail.com>

>
>
> Hello,
>
> I am trying to parse a log file.  I want to sort based on the second
> element the list that is in the file.
>
> What is the best way to do this?  The sort is just on the line itself where
> I want to re-organize the lines based on the second element of the csv file
>
> Thanks,
> Ron
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
You may use the key parameter of sort() or sorted for this.

If your data is homogenous (i.e. all items have the subitem you want to sort
on and all are comparable), maybe something like this would work:

>>> from operator import itemgetter
>>> nested_list = [[9, 0, 5], [19, -10, -3], [-9, 30, -5], [4, 8, 15]]
>>> list_sorted_on_2nd_elem = sorted(nested_list, key=itemgetter(2))
>>> list_sorted_on_2nd_elem
[[-9, 30, -5], [19, -10, -3], [9, 0, 5], [4, 8, 15]]
>>>

2nd element (starting with the 0th one) - actually the 3rd one, otherwise
the index in itemgetter() should be adjusted.

hth,

 Vlasta
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080820/abf4257a/attachment-0001.html>


More information about the Python-list mailing list