Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort multidimensional array by column?

Is there a way to use the sort() method or any other method to sort a list by column? Lets say I have the list:

[ [John,2], [Jim,9], [Jason,1] ] 

And I wanted to sort it so that it would look like this:

[ [Jason,1], [John,2], [Jim,9], ] 

What would be the best approach to do this?

Edit:

Right now I am running into an index out of range error. I have a 2 dimensional array that is lets say 1000 rows b 3 columns. I want to sort it based on the third column. Is this the right code for that?

sorted_list = sorted(list_not_sorted, key=lambda x:x[2]) 
like image 871
Web Hopeful Avatar asked Nov 25 '13 00:11

Web Hopeful


People also ask

Can you sort a multidimensional array?

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative (string) keys will be maintained, but numeric keys will be re-indexed.

How do you sort a two dimensional array by column value?

To sort 2 dimensional array by column value with JavaScript, we can use the array sort method. const arr = [ [12, "AAA"], [12, "BBB"], [12, "CCC"], [28, "DDD"], [18, "CCC"], [12, "DDD"], [18, "CCC"], [28, "DDD"], [28, "DDD"], [58, "BBB"], [68, "BBB"], [78, "BBB"], ]; const sortedArr = arr.

How do I sort an array by a column?

NumPy arrays can be sorted by a single column, row, or by multiple columns or rows using the argsort() function. The argsort function returns a list of indices that will sort the values in an array in ascending value.

How do I sort a multi dimensional array in PHP?

Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.


2 Answers

Yes. The sorted built-in accepts a key argument:

sorted(li,key=lambda x: x[1]) Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]] 

note that sorted returns a new list. If you want to sort in-place, use the .sort method of your list (which also, conveniently, accepts a key argument).

or alternatively,

from operator import itemgetter sorted(li,key=itemgetter(1)) Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]] 

Read more on the python wiki.

like image 53
roippi Avatar answered Sep 27 '22 19:09

roippi


You can use the sorted method with a key.

sorted(a, key=lambda x : x[1]) 
like image 38
squiguy Avatar answered Sep 27 '22 20:09

squiguy