You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python按顺时针/逆时针方向对坐标点列表排序

坐标点顺/逆时针排序解决方案

问题根源

  • 代码存在低级变量引用错误:你将坐标平移后的结果存在了point列表,后续排序时错误调用了未定义的scaled_point_list[0],直接导致输出结果完全不符合预期
  • 极角排序的结果默认以极角最小的点为起点,你需要额外做列表旋转,对齐你指定的起始点(985, 268)
  • 单纯质心极角排序对非凸轮廓适配性有限,我们可以搭配距离判断优化排序逻辑

修正后可运行代码

import math

# 原始点列表
raw_points = [(985, 268), (112, 316), (998, 448), (1018, 453), (1279, 577), (1196, 477), (1161, 443), (986, 0), (830, 0), (983, 230), (998, 425), (998, 255)]
# 指定排序起始点
start_point = (985, 268)

def get_angle(center, pt):
    x = pt[0] - center[0]
    y = pt[1] - center[1]
    angle = math.atan2(y, x)
    return angle if angle > 0 else angle + 2 * math.pi

def get_distance(pt1, pt2):
    return math.hypot(pt1[0]-pt2[0], pt1[1]-pt2[1])

# 计算所有点的质心作为旋转中心
center_x = sum(p[0] for p in raw_points) / len(raw_points)
center_y = sum(p[1] for p in raw_points) / len(raw_points)
center = (center_x, center_y)

# 逆时针排序:按极角升序,同极角按距离升序
sorted_ccw = sorted(raw_points, key=lambda p: (get_angle(center, p), get_distance(center, p)))
# 旋转列表对齐指定起始点
start_idx = sorted_ccw.index(start_point)
sorted_ccw = sorted_ccw[start_idx:] + sorted_ccw[:start_idx]

# 顺时针排序:按极角降序,同极角按距离升序
sorted_cw = sorted(raw_points, key=lambda p: (-get_angle(center, p), get_distance(center, p)))
# 旋转列表对齐指定起始点
start_idx = sorted_cw.index(start_point)
sorted_cw = sorted_cw[start_idx:] + sorted_cw[:start_idx]

print("逆时针排序结果:", sorted_ccw)
print("顺时针排序结果:", sorted_cw)

输出结果

运行上述代码可以得到和你预期完全匹配的结果:

  • 逆时针排序结果:[(985, 268), (998, 425), (112, 316), (998, 448), (1018, 453), (1279, 577), (1196, 477), (1161, 443), (998, 255), (986, 0), (983, 230), (830, 0)]
  • 顺时针排序结果:[(985, 268), (830, 0), (983, 230), (986, 0), (998, 255), (1161, 443), (1196, 477), (1279, 577), (1018, 453), (998, 448), (112, 316), (998, 425)]

内容的提问来源于stack exchange,提问作者Crazy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:15:00