Reputation: 2945
I need to sort a list of names based on the number they are coupled with. An example of the data I have is:
[['Bob Person', 10], ['Josh Winner', 15], ['Jimmy Dexter', 5], ['Mary Goodsprings', 15]]
A normal sort would do this:
[['Bob Person', 10], ['Jimmy Dexter', 5], ['Josh Winner', 15], ['Mary Goodsprings', 15]]
The sort I want to conduct should be based on the largest number they are coupled with. But, if the numbers are equal, then it should resort to names. Like this:
[['Josh Winner', 15], ['Mary Goodsprings', 15], ['Bob Person', 10], ['Jimmy Dexter', 5]]
Notice how Mary and Josh are both tied, but Josh is still out front because J comes before M.
I have pretty much no clue on how to do this, apart from the fact that I should use the key
function of sort()
.
Upvotes: 0
Views: 383
Reputation: 3386
Since the Python sort is guaranteed to be stable (meaning that the order is preserved when multiple items have the same key), you can sort the list in multiple runs. The most important criterion comes last.
import operator
data = [['Bob Person', 10], ['Josh Winner', 15], ['Jimmy Dexter', 5], ['Mary Goodsprings', 15]]
data.sort()
data.sort(key=operator.itemgetter(1), reverse=True)
Upvotes: 0
Reputation: 369304
Use -item[1]
to sort in a descending order, with item[0]
for the numbers tie.
>>> data = [['Bob Person', 10], ['Josh Winner', 15], ['Jimmy Dexter', 5], ['Mary Goodsprings', 15]]
>>> sorted(data, key=lambda item: (-item[1], item[0]))
[['Josh Winner', 15], ['Mary Goodsprings', 15], ['Bob Person', 10], ['Jimmy Dexter', 5]]
Upvotes: 6