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

如何删除坐标列表中X或Y值重复的坐标,仅保留首个对应坐标

坐标列表去重实现方案

核心逻辑:遍历坐标列表时,用集合记录已经出现过的目标轴数值,遇到未记录的数值就保留对应坐标、同时把数值加入集合,遇到已记录的数值直接跳过即可,时间复杂度为O(n),空间复杂度为O(k)(k为去重后的坐标数量),性能表现适配绝大多数使用场景。

按X轴去重(匹配你给出的示例需求)

def deduplicate_by_x(coord_list):
    existed_x = set()
    result = []
    for x, y in coord_list:
        if x not in existed_x:
            existed_x.add(x)
            result.append((x, y))
    return result

# 测试示例
raw_coords = [(682, 547), (682, 548), (638, 657), (638, 658)]
print(deduplicate_by_x(raw_coords))
# 输出:[(682, 547), (638, 657)]

按Y轴去重

只需把判断逻辑替换为Y轴的集合校验即可:

def deduplicate_by_y(coord_list):
    existed_y = set()
    result = []
    for x, y in coord_list:
        if y not in existed_y:
            existed_y.add(y)
            result.append((x, y))
    return result

X或Y任意一项重复就去重

如果要求只要X或Y其中一个数值出现过,就移除后续对应坐标,同时维护两个集合即可:

def deduplicate_by_x_or_y(coord_list):
    existed_x = set()
    existed_y = set()
    result = []
    for x, y in coord_list:
        if x not in existed_x and y not in existed_y:
            existed_x.add(x)
            existed_y.add(y)
            result.append((x, y))
    return result

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:57:01