Sorting according to clockwise point coordinates

前端 未结 7 2175
别跟我提以往
别跟我提以往 2020-12-16 18:18

Given a list in Python containing 8 x, y coordinate values (all positive) of 4 points as [x1, x2, x3, x4, y1, y2, y3, y4] ((xi, yi) are x and y coo

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 18:47

    Based on BERA's answer but as a class:

    code

    import math
    
    def class Sorter:
        @staticmethod    
        def centerXY(xylist):
            x, y = zip(*xylist)
            l = len(x)
            return sum(x) / l, sum(y) / l  
    
        @staticmethod    
        def sortPoints(xylist):  
            cx, cy = Sorter.centerXY(xylist)
            xy_sorted = sorted(xylist, key = lambda x: math.atan2((x[1]-cy),(x[0]-cx)))
            return xy_sorted
    

    test

    def test_SortPoints():
        points=[(0,0),(0,1),(1,1),(1,0)]
        center=Sorter.centerXY(points)
        assert center==(0.5,0.5)
        sortedPoints=Sorter.sortPoints(points)
        assert sortedPoints==[(0, 0), (1, 0), (1, 1), (0, 1)]
    

提交回复
热议问题