popat
popat

Reputation: 69

Sorting image coordinates in python

I want to sort four co-ordinates, for example- (180,120),(100,40),(100,120),(180,40). This co-ordinates will be returned in random order by the code. I want to sort these co-ordinates such that I have tuple in the following order - ((100,40),(100,120),(180,40),(180,120)). How I can achieve this in python?

One more set of co-ordinates are (170,118),(90,44),(80,120),(165,39)

enter image description here

Upvotes: 0

Views: 318

Answers (1)

BBonless
BBonless

Reputation: 127

I think you can just sort based on X axis, then Y axis if X axes are equal,

Maybe something like this?:

Points = [(180,120),(100,40),(100,120),(180,40)];

def Swap(Array, Index1, Index2):
    Temp = Array[Index1];
    Array[Index1] = Array[Index2];
    Array[Index2] = Temp;

def Sort(Array):
    for x in range(0, len(Array) - 1):
        if (Array[x][0] > Array[x+1][0]):
            Swap(Array, x, x+1);
        elif (Array[x][0] == Array[x+1][0]):
            if (Array[x][1] > Array[x+1][1]):
                Swap(Array, x, x+1);

Aight I did not know you could just call sorted() as shown by mozway, that is very convenient

Upvotes: 2

Related Questions