0

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]]
Wailan Tirajoh
  • 481
  • 5
  • 17
  • Right, so what went wrong with what you found about sorting by multiple items in sublists? – roganjosh Oct 22 '19 at 18:00
  • Can you explain *why* this is the expected output? And what have you tried to solve this problem? – Scott Hunter Oct 22 '19 at 18:01
  • Also note that you're calling this an "array" but it isn't in Python, it's a list. 99% of the the time, "array" refers to NumPy array. There is also a Python array but it's barely ever used. – roganjosh Oct 22 '19 at 18:03
  • Aw i think i just solved my own problem by search at stackoverflow with your keyword mates @roganjosh i found itemgetter and it solved my own question like with 3 repeat lines – Wailan Tirajoh Oct 22 '19 at 18:11

2 Answers2

1

If you want to do in place sort than

arr.sort(key=lambda x:(x[1], -x[0])

otherwise can use sorted

sortedArray = sorted(arr, key=lambda x: (x[1], -x[0]))

PraveenB
  • 1,270
  • 10
  • 11
0

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.

orlp
  • 112,504
  • 36
  • 218
  • 315