471,873 Members | 1,842 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,873 software developers and data experts.

python sorting 2dim. array ?

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)
Sep 25 '08 #1
3 1667
remark: The server is using python server version 2.3.4
Sep 25 '08 #2
fr*****@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/progra...form-in-python

Peter
Sep 25 '08 #3
fred...@fulladsl.be:
list[rowindex][colomindex]
I want to sort on the second colom as first (and as
second sortfield the first colom).
A good way, in Python 2.5:
>>from operator import itemgetter
a = [[1, 2], [3, 1], [2, 5], [7, 1]]
a.sort(key=itemgetter(1, 0))
a
[[3, 1], [7, 1], [1, 2], [2, 5]]

Bye,
bearophile
Sep 25 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

226 posts views Thread by Stephen C. Waterbury | last post: by
7 posts views Thread by Federico G. Babelis | last post: by
2 posts views Thread by Jeroen Ceuppens | last post: by
6 posts views Thread by Alex Snast | last post: by
11 posts views Thread by Thomas Heller | last post: by
5 posts views Thread by jrod11 | last post: by
reply views Thread by zermasroor | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.