How to sort two dimensional list while giving priority along one of the dimension

Viewed 303

I am trying to sort a two-dimensional list while prioritizing sorting along one of the dimensions.

Example:

twod_list = [[116.2,103.4],[124.9,103.4],[129.5,103.4],
             [144.6,103.4],[148.9,103.4],
             [119.1,109.3],[125.9,103.4],[146.3,109.3],[135.8,103.4]]

I am trying to sort this in the following order, first sort along the second dimension, then sort along the first dimension while maintaining the order on the second dimension. So my expected sorted list looks like below

sorted_twod_list = [[116.2,103.4],[124.9,103.4],[125.9,103.4],[129.5,103.4],[135.8,103.4],
             [144.6,103.4],[148.9,103.4],
             [119.1,109.3],[146.3,109.3]]

I tried to sort first along the second dimension then on the first dimension but in doing so it is changing the order.

twod_list = [[116.2,103.4],[124.9,103.4],[129.5,103.4],
             [144.6,103.4],[148.9,103.4],
             [119.1,109.3],[124.9,103.4],[146.3,109.3],[135.8,103.4]]
twod_sorted_on_y = sorted(twod_list,key=lambda l:l[1])
twod_sorted = sorted(twod_sorted_on_y,key=lambda l:l[0])

I am getting the following result:

twod_sorted = [[116.2, 103.4],[119.1, 109.3],[124.9, 103.4],
               [124.9, 103.4],[129.5, 103.4],
               [135.8, 103.4],[144.6, 103.4],[146.3, 109.3],[148.9,103.4]]

We can also accomplish this using if condition, but I want to know whether any short cut exists using numpy or pandas?

2 Answers

You need to consider both values in the same sort key. Normally, Python would sort by the [0] value, then by the [1] value. We can make use of this by creating a key that reverses the values:

sorted(twod_list,key=lambda l:(l[1], l[0]))

Now Python will sort first according to the [0] of the key, which is [1] of the original, and then according to the [1] of the key, which is [0] of the original.

You can use the function itemgetter(1, 0) as a key in the sorted() function:

from operator import itemgetter

sorted(twod_list, key=itemgetter(1, 0))
Related