Reputation: 87
So I have this list:
lst = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]
I want to sort it accordingly: in reverse order for the first index, and if 2 items have the same first index, then in normal order by the second index
So the output will be:
lst = [[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]]
I can do this using lambda function:
lst = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]
lst.sort(key = lambda x : (-x[0], x[1]))
But if I dont want to use lambda, how would I do it? I have this template, but not sure how to proceed from here:
lst = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]
def compare(input):
# put code here
lst.sort(key = compare(#what and how do I pass as input))
Upvotes: 0
Views: 362
Reputation: 42143
Python's sort is "stable" so it will keep items with the same sort key in their original relative order. This means that you can perform two sorts, starting with the least significant order and obtain the result you are looking for:
lst = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]
from operator import itemgetter
lst.sort(key=itemgetter(1)) # ascending 2nd index
lst.sort(key=itemgetter(0),reverse=True) # descending 1st index (stable)
print(lst)
[[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]]
If you need to use a custom comparison function, you will find a solution here.
Upvotes: 1