close

How to sort a list of x-y coordinates

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to sort a list of x-y coordinates in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to sort a list of x-y coordinates?

  1. How to sort a list of x-y coordinates?

    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)

  2. sort a list of x-y coordinates

    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)

Method 1

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.

Method 2

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)

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read