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

如何使用循环计算折线(Polyline)长度?(Python实现)

计算折线总长度的Python实现

实现思路

  • 遍历坐标列表中的每一对相邻点
  • 对每对点使用欧几里得距离公式计算两点间距
  • 累加所有相邻点的距离得到折线总长度
  • 加入边界情况处理:空坐标集或仅单个点时返回0,避免索引错误

代码实现

import math

def calculate_polyline_length(coords):
    total_length = 0.0
    # 遍历每一对相邻坐标点
    for i in range(len(coords) - 1):
        x1, y1 = coords[i]
        x2, y2 = coords[i+1]
        # 应用距离公式计算两点间距
        distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
        total_length += distance
    return total_length

# 测试给定的坐标集合
coords = [[1.0, 1.0], [1.5, 2.0], [2.2, 2.4], [3.0, 3.2], [4.0, 3.6], [4.5, 3.5], [4.8, 3.2], [5.2, 2.8], [5.6, 2.0],
          [6.5, 1.2]]
print(calculate_polyline_length(coords))

代码适配性说明

这个函数可以直接适配任意格式为[[x1,y1], [x2,y2], ...]的坐标集合:

  • 无论坐标点数量多少,只要是二维点的列表结构就能正常计算
  • 自动处理空列表或仅含单个点的情况,返回合理的0值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:45:32