Reputation: 2615
In python, one can perform a sort on a list using sorted(list)
or list.sort()
. These functions support sorting by various stages (primary sort, secondary sort, etc.). I know that one can reverse the sort by supplying reversed=True
to the function.
My question is: How can I sort a list and reverse a single stage of the sort?
For example: I have a list to be sorted, which contains objects that store both the time they were created and a name. Now I want to sort them primarily by time (higher value = newer) and secondarily by name (a-z).
If I do sorted(list_of_objects, key=lambda x: (x.time, x.name))
, then the older ones (lower time value) would be at the top, but the alphabetical sorting would be correct (a-z).
If I do sorted(list_of_objects, key=lambda x: (x.time, x.name), reversed=True)
to reverse the sort, the newer elements (higher time value) are at the top but the alphabetical sorting would be reversed too (z-a).
As stated before, I want to reverse only one stage of the sort. In this example, the primary stage.
How, if at all, can this be done?
For integers, one could subtract the value to be sorted from the maximum value it can reach, thus reversing the sort, but this technique isn't applicable for other data types such as strings.
Upvotes: 1
Views: 158
Reputation:
This is covered in Sort stability and complex sorts:
Sorts are guaranteed to be stable [...] This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade
So in your case, you could do
s = sorted(list_of_objects, key=lambda x: x.name) # sort on secondary key
sorted(list_of_objects, key=lambda x: x.time, reverse=True) # now sort on primary key, descending
(Comments in the code are taken verbatim from the linked Python docs)
Upvotes: 4