pythonarrayslistsortingmultidimensional-array

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], ... ]

Solution

  • 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], ...]