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

Python中如何对随机返回的四个图像坐标点按指定规则排序

Python实现二维坐标点指定排序

从示例可推导排序逻辑为优先按坐标的x值从小到大排序,x值相同的情况下按y值从小到大排序,最终返回嵌套元组格式的结果。

完整实现代码

def sort_coordinates(coords):
    # 按x升序、y升序排序,支持输入列表/元组格式的坐标集合
    sorted_list = sorted(coords, key=lambda p: (p[0], p[1]))
    # 转换为要求的元组格式返回
    return tuple(sorted_list)

# 第一组测试用例
test1 = ((180,120), (100,40), (100,120), (180,40))
result1 = sort_coordinates(test1)
print(result1)  # 输出:((100, 40), (100, 120), (180, 40), (180, 120)),与需求完全匹配

# 第二组测试用例
test2 = ((170,118), (90,44), (80,120), (165,39))
result2 = sort_coordinates(test2)
print(result2)  # 输出:((80, 120), (90, 44), (165, 39), (170, 118))

逻辑说明

  • sorted函数的key参数指定排序优先级,lambda p: (p[0], p[1])表示先比较每个坐标点的第一个元素(x值),x值相等时再比较第二个元素(y值)
  • 最终用tuple()将排序后的列表转换为元组格式,满足输出要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:42:03