0

Case: I want to sort a list of objects on two attributes. The first one is an integer which represents the points scored. The second attribute is a datetime.timedelta object.

My goal: I want to sort the list first on the score (highest on top), and after on timedelta (shortest/smallest first). The end result should be a list ordered on the score, and when there is an even score the time should decide who wins by the shortest time.

I have the following code:

    def show_result_full(self):
        result = self.sessions.all()
        result.sort(key=lambda x: (x.score, x.session_time), reverse=True)

Steps in code:

  1. Get all sessions
  2. Sort the sessions as described above

This does not work because now it's reversed on both attributes. Looking forward to your suggestions because I am really stuck on this.

balderman
  • 22,927
  • 7
  • 34
  • 52
  • `result.sort(key=lambda x: (-x.score, x.session_time))` (Note the `-`.) – alani Oct 03 '20 at 19:49
  • 1
    Does this answer your question? https://stackoverflow.com/questions/37693373/sort-python-list-with-two-keys-but-only-one-in-reverse-order – Fried Noodles Oct 03 '20 at 19:51
  • See similar question https://stackoverflow.com/questions/63517942/sort-a-dictionary-by-values-in-ascending-order-and-by-keys-in-descending-order which I answered previously, although in that case the primary key was ascending and the secondary was descending. – alani Oct 03 '20 at 19:51
  • Does this answer your question? [sort Python list with two keys but only one in reverse order](https://stackoverflow.com/questions/37693373/sort-python-list-with-two-keys-but-only-one-in-reverse-order) – Pranav Hosangadi Oct 03 '20 at 19:53

1 Answers1

0

what about sorting them one by one? first the secondary condition, secondly the primary one? to make it clear - created a list of numbers from 10 to 29, sort them first by the second number in reverse order, and then by first number not in reverse order

a = [str(i) for i in range(10,29)]
a.sort(key = lambda x: x[1], reverse=True)
a.sort(key = lambda x: x[0])
print(a)

I got this, as I was expected, as output:

['19', '18', '17', '16', '15', '14', '13', '12', '11', '10', '28', '27', '26', '25', '24', '23', '22', '21', '20']

The numbers are sorted such that the first number ordered in increasing order, and the second number in decreasing.

Yossi Levi
  • 1,258
  • 1
  • 4
  • 7