pythonarrayslistsortingmultidimensional-array

Python Sort Multidimensional List first element Based on second element that already sorted


I have a multidimensional List like this (the second element already sorted)

[[92, 25], [93, 25], [95, 27], [94, 27], [94, 27], [92, 27], [89, 27], [89, 27], [92, 27], [91, 30], [90, 30], [90, 30], [90, 30], [91, 30]]

So i want to sort the first element base on the second element (Descending). Expected Output:

[[93, 25], [92, 25], [95, 27], [94, 27], [94, 27], [92, 27], [92, 27], [89, 27], [89, 27], [91, 30], [91, 30], [90, 30], [90, 30], [90, 30]]

Solution

  • Let me get this straight, you want a list to be sorted first based on the second element in a tuple in ascending order, and break any ties by the first element in descending order?

    You can do that with sorted(l, key=lambda x: (x[1], -x[0])), assuming your elements are numbers. If not you have to write a more complex comparison function.