Sebastian G Sebastian G - 5 months ago 75x
Python Question

How to sort a list of x-y coordinates

i want to sort a list of points which looks like:

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

The pattern it should be sortet after is:

The y values are superiour, that means the lowest y values should be at the top of the array. Then the x values should be sorted in ascending order. 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.


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.