1

So I have this list with sublists:

[[39, 4, 43], [23, 3, 26], [46, 5, 51], [66, 15, 51], [66, 7, 73], [10, 2, 12], [79, 8, 87]]

I need to sort the lists in order of the third element in each sub-list. But in case two or more of them are equals like in this case:

[46, 5, 51], [66, 15, 51]

the algorithm when sorting should put first the sublist with the biggest first element, so the wanted output should be like this.

 [[79, 8, 87],[66, 7, 73],[66, 15, 51],[46, 5, 51],[39, 4, 43],[23, 3, 26],[10, 2, 12]]

Any tip to go through this? thanks or your time and help

  • 2
    Possible duplicate of [How to sort (list/tuple) of lists/tuples?](https://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples) – G. Anderson Mar 26 '19 at 19:44

2 Answers2

8

You can set up your sort order as a tuple like this:

l = [[39, 4, 43], [23, 3, 26], [46, 5, 51], [66, 15, 51], [66, 7, 73], [10, 2, 12], [79, 8, 87]]

sorted(l, key = lambda x: (x[2],x[0]), reverse=True)

result:

[[79, 8, 87], [66, 7, 73], [66, 15, 51], [46, 5, 51], [39, 4, 43], [23, 3, 26], [10, 2, 12]]

Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
2

There is also itemgetter to do this kind of sorting:

from operator import itemgetter

l = [[39, 4, 43], [23, 3, 26], [46, 5, 51], [66, 15, 51], [66, 7, 73], [10, 2, 12], [79, 8, 87]]

sorted(l, key=itemgetter(2, 0), reverse=True)
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75