Connecting Tech Pros Worldwide Forums | Help | Site Map

python sorting 2dim. array ?

fredo66@fulladsl.be
Guest
 
Posts: n/a
#1: Sep 25 '08
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)

fredo66@fulladsl.be
Guest
 
Posts: n/a
#2: Sep 25 '08

re: python sorting 2dim. array ?


remark: The server is using python server version 2.3.4
Peter Otten
Guest
 
Posts: n/a
#3: Sep 25 '08

re: python sorting 2dim. array ?


fredo66@fulladsl.be wrote:
Quote:
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)
Quote:
Quote:
Quote:
>>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
bearophileHUGS@lycos.com
Guest
 
Posts: n/a
#4: Sep 25 '08

re: python sorting 2dim. array ?


fred...@fulladsl.be:
Quote:
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:
Quote:
Quote:
Quote:
>>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
Closed Thread