1

Let's say my_list is a list of datetime objects. I understand that I can sort this list with the most recent dates first with:

sorted(my_list, reverse=True)

Similarly, if I have a list of tuples (datetime, str). Then I can sort this with most recent first by:

sorted(my_list, lambda x: x[0], reverse=True)

But what if I want to sort by datetime, most recent first, and break ties by sorting the str "alphabetically"?

sorted(my_list, lambda x: x[0], x[1], reverse=True)

Now this will also sort the string in reverse alphabetical order. How do I fix it to do what I want?

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • As an aside: You really don't need the lambda functions to pull tuple entries, python will sort by tuple index 0, then 1. However this doesn't address the ascending/descending issue. – RufusVS Dec 14 '20 at 19:18
  • Does this answer your question? [Sort by multiple keys using different orderings](https://stackoverflow.com/questions/11476371/sort-by-multiple-keys-using-different-orderings) – Jay Mody Dec 14 '20 at 19:33
  • @RufusVS Good point. Consider this an over-simplified example for a situation where a lambda would be required. – Code-Apprentice Dec 14 '20 at 23:02
  • @JayMody Thanks for the link. I think it doesn't answer my question because the answers attempt to be more general than the specific case I'm asking here. – Code-Apprentice Dec 14 '20 at 23:04

1 Answers1

3

You can change your datetime objects so that they sort in the order you want. A simple subtraction will convert them to datetime.timedelta objects.

latest = max(x[0] for x in my_list) # the latest datetime in your list
my_sorted_list = sorted(my_list, key=lambda x: (latest - x[0], x[1]))
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Rather than waste the time finding the max time in the list, you could choose an arbitrary date. You'd just get negative deltas for sort keys. – RufusVS Dec 14 '20 at 19:23
  • @RufusVS yes that is true. And if you picked an arbitrary date far into the future, they'd all be positive but the order would be the same. I just thought my point was easier to understand if I subtracted from something meaningful. – Mark Ransom Dec 14 '20 at 19:28
  • Makes sense. This is analogous to using `-x` as a key for sorting an int value highest to lowest. – Code-Apprentice Dec 14 '20 at 23:05