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?