1

I have a list of XY co-ordinates, and I am looking for a way to sort them as they appear on the plot with top-to-bottom, left-to-right precedence.

I tried sorting them as a tuple in Python but it didn't work.

Here are the (normalized) co-ordinates:

(0.48425699105850684, 0.4852200502470339) (0.8003207976544613, 0.1794844315136523) (0.663158173206857, 0.19739922702645016) (0.26770425263394393, 0.20288883507443173) (0.5214529814719886, 0.2032096846467844) (0.4768268032594222, 0.3875097802042241) (0.5400594055964151, 0.5870619715600098) (0.5445470099105095, 0.8064964338255158)

fortyTwo102
  • 113
  • 1
  • 9

2 Answers2

1

So you need to use Y-coordinate as primary key, X-coordinate as secondary key.
One of possible ways in Python:

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

if your Y-axis direction is down (otherwise -x[1])

Example:

lst = [(3, 8), (5, 3), (1, 5), (2, 3), (7, 4), (4, 5)]
lst.sort(key = lambda x: (x[1], x[0]))
print(lst)

>>[(2, 3), (5, 3), (7, 4), (1, 5), (4, 5), (3, 8)]
MBo
  • 77,366
  • 5
  • 53
  • 86
0

I eventually ended up using the product of the X and Y coordinates as the sorting key. It worked for my test cases!

fortyTwo102
  • 113
  • 1
  • 9