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

1

2 Answers 2

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]]

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.