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

Python迭代移除列表中与相邻元素距离过近的坐标点

坐标列表过滤:移除与前序保留点欧氏距离过近的点

需求明确

需要过滤由(x,y)坐标元组组成的列表,规则为:

  • 从第一个点开始,保留该点后,跳过所有与它欧氏距离小于阈值的后续点,直到找到第一个距离≥阈值的点并保留
  • 以新保留的点为基准,重复上述过程,直到遍历完所有坐标

原代码问题分析

第一段代码无效原因

  1. 未初始化变量i:循环前未给i赋值(如i=0),导致循环根本无法执行,原列表无变化
  2. 删除方式错误:使用remove(coordinateList[i+1])是按值删除第一个匹配元素,若列表存在重复坐标会误删前置元素;正确做法是用del按索引删除

第二段代码逻辑缺陷

仅基于原列表的固定索引i判断,没有以最后一个保留的坐标为基准往后查找,无法实现连续跳过过近点的需求

正确解法:构建新列表实现(推荐)

这种方式逻辑清晰,避免修改原列表时的索引混乱:

import math

def filter_coordinates(coords, threshold=50):
    if not coords:
        return []
    # 初始化结果列表,第一个点直接保留
    filtered = [coords[0]]
    idx = 1
    while idx < len(coords):
        # 计算最后一个保留点与当前点的欧氏距离
        last_x, last_y = filtered[-1]
        curr_x, curr_y = coords[idx]
        distance = math.sqrt((last_x - curr_x)**2 + (last_y - curr_y)**2)
        if distance >= threshold:
            filtered.append(coords[idx])
            idx += 1
        else:
            # 距离过近,跳过当前点
            idx += 1
    return filtered

# 示例使用
coordinateList = [(0,0), (10,10), (60,60), (70,70), (120,120)]
result = filter_coordinates(coordinateList)
print(result)
# 输出: [(0, 0), (60, 60), (120, 120)]

代码说明

  • 先处理空列表的边界情况,避免索引错误
  • 用filtered存储最终保留的坐标,初始加入第一个点
  • 用idx指针遍历原列表,每次以filtered最后一个元素为基准判断:
    • 距离≥阈值:加入结果列表,指针后移
    • 距离<阈值:直接跳过当前点,指针后移

原代码修复版(原地修改)

如果一定要在原列表上修改,需修正初始化和删除逻辑:

import math

coordinateList = [(0,0), (10,10), (60,60), (70,70), (120,120)]
threshold = 50
i = 0  # 必须初始化i
length = len(coordinateList)
while i < length - 1:  # 避免i+1越界
    last_x, last_y = coordinateList[i]
    curr_x, curr_y = coordinateList[i+1]
    distance = math.sqrt((last_x - curr_x)**2 + (last_y - curr_y)**2)
    if distance < threshold:
        del coordinateList[i+1]  # 按索引删除目标元素
        length -= 1
    else:
        i += 1

print(coordinateList)
# 输出: [(0, 0), (60, 60), (120, 120)]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 08:52:29