Sorting according to clockwise point coordinates

前端 未结 7 2172
别跟我提以往
别跟我提以往 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:37

    You should use a list of 2-item tuples as your data structure to represent a variable number of coordinates in a meaningful way.

    from functools import reduce
    import operator
    import math
    coords = [(0, 1), (1, 0), (1, 1), (0, 0)]
    center = tuple(map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), coords), [len(coords)] * 2))
    print(sorted(coords, key=lambda coord: (-135 - math.degrees(math.atan2(*tuple(map(operator.sub, coord, center))[::-1]))) % 360))
    

    This outputs:

    [(0, 0), (0, 1), (1, 1), (1, 0)]
    

提交回复
热议问题