[Tutor] Sorting 2-d data

Lie Ryan lie.1296 at gmail.com
Sun Sep 13 07:17:45 CEST 2009


Wayne wrote:
> Hi,
> 
> I have a set of data that looks something like this:
> 
> 3, 4, 3, 2, 1
> 2, 1, 1, 1, 1
> 4, 2, 2, 1, 2
> 1, 3, 1, 1, 1
> 
> I want to be able to sort it by the first column, keeping the rest of 
> the values in the same position relative to the original:
> 
> 1, 3, 1, 1, 1
> 2, 1, 1, 1, 1
> 3, 4, 3, 2, 1
> 4, 2, 2, 1, 2
> 
> and I'm wondering if there are any included ways to sort data like this. 
> I've currently got a 2d list by columns, but I could easily convert that 
> to rows if it would work better.
> 

if you have data like this:
mylist = [
     [3, 4, 3, 2, 1],
     [2, 1, 1, 1, 1],
     [4, 2, 2, 1, 2],
     [1, 3, 1, 1, 1],
]

you can use mylist.sort(key=lambda x: x[0])

sorted(mylist, key=lambda x: x[0]) works as well if you need a new list

if your data is like this:
mylist = [
     [3, 2, 4, 1],
     [4, 1, 2, 3],
     [3, 1, 2, 1],
     [2, 1, 1, 1],
     [1, 1, 2, 1],
]

you can use zip(*mylist) to transform your data to row-first list, sort 
using the above method, then zip(*mylist) again. Beware that 
zip(*mylist) returns a list of tuples even if the original data is list 
of lists. I think there should be an easier (and faster) way, that 
others can point out.



More information about the Tutor mailing list