Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort multidimensional array based on 2nd element of the subarray

I have an array like this:

[['G', 10], ['A', 22], ['S', 1], ['P', 14], ['V', 13], ['T', 7], ['C', 0], ['I', 219]] 

I'd like to sort it based on the 2nd element in descending order. An ideal output would be:

[['I', 219], ['A', 22], ['P', 14], ... ] 
like image 456
Federico Capello Avatar asked Nov 20 '13 15:11

Federico Capello


People also ask

Can you sort a multidimensional array?

You can sort by any key (also nested like 'key1. key2. key3' or ['k1', 'k2', 'k3'] ) It works both on associative and not associative arrays ( $assoc flag)

How do you sort a 2D array?

To column-wise sort a 2D Array in Java, call the “Arrays. sort()” method with a “Comparator interface”. A Comparator interface defines a “compare()” method that accepts two parameters and then compares them with each other. If the passed parameters are equal, it returns zero.

How do you sort a two dimensional list?

How do you sort a 2D list in Python using lambda? Use sorted() with a lambda function to sort a multidimensional list by column. Call sorted(iterable, key=None) with key set to a lambda function of syntax lambda x: x[i] to sort a multidimensional list iterable by the i th element in each inner list x .


2 Answers

list.sort, sorted accept optional key parameter. key function is used to generate comparison key.

>>> sorted(lst, key=lambda x: x[1], reverse=True) [['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]  >>> sorted(lst, key=lambda x: -x[1]) [['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...]  >>> import operator >>> sorted(lst, key=operator.itemgetter(1), reverse=True) [['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...] 
like image 84
falsetru Avatar answered Oct 03 '22 13:10

falsetru


Use itemgetter

from operator import itemgetter a = [[1, 3, 5], [2, 511, 7], [17, 233, 1]] a = sorted(a, key=itemgetter(1)) 

Output : [[1, 3, 5], [17, 233, 1], [2, 511, 7]]

itemgetter can also be used to sort by multiple subarrays.

like image 30
Nikhil Kollanoor Avatar answered Oct 03 '22 14:10

Nikhil Kollanoor