how to sort a multidimensional array with one column in ascending order and another column in descending order?

Viewed 383

My question is about two dimensional list sort in Python,a third party toolkit is not allowed for this question.

Suppose there is a two dimensional Students list which stores the information of some student,the first column is id,the second is name,the third is age,you are required to sort the list according to age as first keyword in descending order,but name as second keyword in ascending order,that is,if studentA and studentB are of the same age,then sort the list by name in ascending order.

the ref code is as below,

students = [[3 , 'Jack' , 12] , [2 , 'Rose' , 13] , [1 , 'Tom' , 10] , [5 , 'Sam' , 12] , [4 , 'Joy' , 8]]
print(f"according to age as first keyword,name as second keyword in reverse order:\
{sorted(students , key=(lambda x: [x[2] , x[1]]) , reverse=True)}")

and the output is

[[2, 'Rose', 13], [5, 'Sam', 12], [3, 'Jack', 12], [1, 'Tom', 10], [4, 'Joy', 8]]

but the desired result is

[[2, 'Rose', 13],  [3, 'Jack', 12], [5, 'Sam', 12], [1, 'Tom', 10], [4, 'Joy', 8]]

how can we modify the code to get the right outcome? Many thanks.

2 Answers

You can use the key but with a small change, and using - counts as "descending" (negative numbers always come before positive numbers in an ascending order sort). So you don't have to use the reverse parameter at all.

>>> sorted(students, key = lambda x:(-x[2], x[1]))
[[2, 'Rose', 13], [3, 'Jack', 12], [5, 'Sam', 12], [1, 'Tom', 10], [4, 'Joy', 8]]

try this:

import operator 
list1 = sorted(students, key=operator.itemgetter(2), reverse=True)
print(list1)
Related