26

I need to sort a list of [x,y] coordinates that looks like this:

list = [[1,2],[0,2],[2,1],[1,1],[2,2],[2,0],[0,1],[1,0],[0,0]]

The pattern I'm looking for after sorting is:

[x,y] coordinate shall be sorted by y first and then by x. The new list should look like:

list = [[0,0],[1,0],[2,0],[0,1],[1,1],[2,1],[0,2],[1,2],[2,2]]

I can't figure out how to do it and would appreciate some help.

Abbas
  • 3,872
  • 6
  • 36
  • 63
  • 1
    Also the faster and cleaner answer isn't here. Which would be `my_list = np.array(list) ind = np.lexsort((my_list[:,1], mylist[:,0])) sorted = my_list[ind]` – Jesse Reza Khorasanee May 14 '19 at 23:13

2 Answers2

54

use sorted with key:

>>> my_list = [[1,2],[0,2],[2,1],[1,1],[2,2],[2,0],[0,1],[1,0],[0,0]]
>>> sorted(my_list , key=lambda k: [k[1], k[0]])
[[0, 0], [1, 0], [2, 0], [0, 1], [1, 1], [2, 1], [0, 2], [1, 2], [2, 2]]

It will first sort on the y value and if that's equal then it will sort on the x value.

I would also advise to not use list as a variable because it is a built-in data structure.

AKS
  • 18,983
  • 3
  • 43
  • 54
-3

Define a virtual index Z = (X+Y) now perform quick sort on Z and based on index Z pick elements (X, Y). Points on circle will lead to same Z (and obviously will stick together in sort results)

SACn
  • 1,862
  • 1
  • 14
  • 29
  • 8
    this can't work because the coordinates `(3,11)` and `(11,3)` would give you the same `Z` when in reality they're very different points – Jona May 10 '19 at 20:47