Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort 2d array by row in python?

Tags:

python

sorting

I have 2d array, dimension 3x10, and I want to sort by values in 2nd row, from lowest to highest value.

like image 490
user257522 Avatar asked Jan 31 '10 23:01

user257522


1 Answers

How does your "2D array" look like?

For example:

>>> a = [
     [12, 18, 6, 3], 
     [ 4,  3, 1, 2], 
     [15,  8, 9, 6]
]
>>> a.sort(key=lambda x: x[1])
>>> a
[[4,  3,  1, 2], 
 [15, 8,  9, 6], 
 [12, 18, 6, 3]]

But I guess you want something like this:

>>> a = [
     [12, 18, 6, 3], 
     [ 4,  3, 1, 2], 
     [15,  8, 9, 6]
]
>>> a = zip(*a)
>>> a.sort(key=lambda x: x[1])
>>> a
[(6,  1,  9), 
 (3,  2,  6), 
 (18, 3,  8), 
 (12, 4, 15)]
>>> a = zip(*a)
>>> a
[(6, 3, 18, 12), 
 (1, 2,  3,  4), 
 (9, 6,  8, 15)
]
like image 150
Messa Avatar answered Sep 19 '22 03:09

Messa