-2

I have a list of lists as myList = [['a',1],['b',4],['a',5], ['b',6]].I want to sort this list alphabetically with first element as the key which I can do as myList.sort(key=lambda x:x[0]) which changes myList to [['a', 1], ['a', 5], ['b', 4], ['b',6]]. But if the first elements of the inner lists are the same, I want to sort it in descending order of the second element of the inner list and get the result as [['a', 5], ['a', 1], ['b', 6], ['b',4]]. What is the cleaner way to do it? I could have done this in Javascript as

myList.sort((a,b) => {
    if(a[0] == b[0]){
        return b[1] > a[1]
    } else {
        return b[0] < a[0]
    }
})

How do I achieve this in python?

1 Answers1

3

Use a tuple as a key:

myList.sort(key=lambda x:(x[0], -x[1]))

# myList = [['a', 5], ['a', 1], ['b', 6], ['b', 4]]
Gavin Haynes
  • 1,721
  • 11
  • 21
  • 1
    The key is a lambda function that returns a tuple of the ordering. First the leftmost element is compared; if they're equal, the second, and so on. `-` makes the sort descending instead of ascending for a particular "column" of numbers. – ggorlen Dec 31 '19 at 19:38