Assume we have a list of 5 tuple:
(a, b , c, d, e)
Let the list be student_tuples.
I wish to sort the list different orders for different fields.
The below mentioned command
sorted(student_tuples, key=itemgetter(2,4,0,1))
Will sort the list on ascending order for all the fields.
The below mentioned command
sorted(student_tuples, key=itemgetter(2,4,0,1), reverse=true)
Will sort the list on descending order for all the fields.
What I am looking for is sorting a list on different orders for different fields.
Is there a easy way to do so.
Based on the answers the technique could be used in any language
Thanks,
Gudge
If the values are numeric, you can do this easily using
lambda:If you can’t easily negate the order inside a lambda function, you need to rely on the stableness of python sorting and sort a few times:
I explain it in more depth in this answer.
Proof that my answers above accomplish the same thing (with numeric input):