根据顺时针点坐标排序

给定Python中的一个列表,该列表包含4个点的8个x,y坐标值(全部为正数),如[x1, x2, x3, x4, y1, y2, y3,y4](xi, yi)第i个点的x和y坐标),

如何排序新列表[a1, a2, a3, a4, b1, b2, b3, b4](ai, bi)使1 2 3

4的坐标按顺时针方向排列,其中1最接近xy平面的原点,即类似

          2--------3

| |

| |

| |

1--------4

点将大致形成平行四边形。

目前,我正在考虑找到(x + y)的最小值的点为1,然后通过剩余坐标中x的最小值的点为2,通过(x + y)的最大值为3的点作为剩余点

回答:

您应该使用2项元组的列表作为数据结构,以有意义的方式表示可变数量的坐标。

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))

输出:

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

以上是 根据顺时针点坐标排序 的全部内容, 来源链接: utcz.com/qa/400039.html

回到顶部