给出Python中包含4个点的8个x,y坐标值(均为正数)的列表,作为[x1, x2, x3, x4, y1, y2, y3, y4]((xi, yi)是第i个点的x和y坐标),
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 coordinates of ith point ),
如何对其进行排序,以使新列表[a1, a2, a3, a4, b1, b2, b3, b4]使得1 2 3 4的坐标(ai, bi)顺时针排列,其中1最接近xy平面的原点,即类似
How can I sort it such that new list [a1, a2, a3, a4, b1, b2, b3, b4] is such that coordinates (ai, bi) of 1 2 3 4 are clockwise in order with 1 closest to origin of xy plane, i.e. something like
2--------3 | | | | | | 1--------4点将大致形成平行四边形.
Points will roughly form a parallelogram.
当前,我正在考虑找到(x + y)最小值的点为1,然后通过剩余坐标中x最少的点找到2,通过(x + y)最大值取3,剩下的为4点
Currently, I am thinking of finding point with least value of (x+y) as 1, then 2 by the point with least x in remaining coordinates, 3 by largest value of (x + y) and 4 as the remaining point
推荐答案您应该使用2项元组列表作为数据结构,以有意义的方式表示可变数量的坐标.
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))这将输出:
[(0, 0), (0, 1), (1, 1), (1, 0)]更多推荐
根据顺时针点坐标排序
发布评论