Reputation: 13
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
Upvotes: 1
Views: 1181
Reputation: 17008
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)
Upvotes: 2
Reputation: 7510
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]]
Upvotes: 8