根据顺时针点坐标排序 [英] Sorting according to clockwise point coordinates

查看:992
本文介绍了根据顺时针点坐标排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出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)]

这篇关于根据顺时针点坐标排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆