I have a list of tuples having coordinates in (x,y) format. I want to sort/arrange it in counter-clockwise direction. ex:
[(0,1),(3,1),(-1,0),(2,2)]
The arranged list should be:
[(3,1),(2,2),(0,1),(-1,0)]
Note: The list can have 'n' of tuples and (0,0) can be a part of list.
You could use the 2-argument arctangent to compute the angle from (1, 0) and use that to sort:
>>> vec = [(0,1),(3,1),(-1,0),(2,2)]
>>> sorted(vec, key=lambda p: math.atan2(p[1], p[0])) # atan2(y, x)
[(3, 1), (2, 2), (0, 1), (-1, 0)]
(Image courtesy of Wikipedia.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With