python sorting 2dim. array ?
Peter Otten
__peter__ at web.de
Thu Sep 25 04:47:10 EDT 2008
fredo66 at fulladsl.be wrote:
> hello,
> Can someone help me with this:
> I have a array like this
>
> list[rowindex][colomindex]
>
> where rows are the records and colom the fields. If I use the .sort()
> method on 'list' the data is sorted on the items of the first colom.
> But I want to sort on the second colom as first (and as second
> sortfield the first colom).
>
> What is the shortest code for this pls ?
>
> (all fields are text value, first colom is name, second category)
>>> items = [(1,2), (2,2), (2,1)]
>>> items.sort(lambda x, y: cmp(x[1::-1], y[1::-1]))
>>> items
[(2, 1), (1, 2), (2, 2)]
If you want something more efficient, see
http://www.python.org/doc/faq/programming/#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python
Peter
More information about the Python-list
mailing list