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

Python循环中创建多变量列表 无额外包计算两组坐标的距离

实现坐标距离计算的方案

原有代码的核心问题

  • 坐标字符串未转换为数值类型,直接执行减法运算会报错
  • split('',1)写法错误,空字符串作为分割参数会抛出语法异常
  • 内层循环中提前return,导致仅计算第一个坐标对就提前终止函数
  • 尝试直接用字符串作为变量名赋值的逻辑不符合Python语法规范

实现代码(仅使用Python标准库,无第三方依赖)

直接使用Python自带的math模块计算平方根,符合无第三方包的要求:

import math

def distances_y(x, y):
    # 最终返回的嵌套列表,顺序和y的顺序一一对应
    all_distances = []
    for y_coord_str in y:
        # 转换当前y坐标为浮点型
        y_coord = [float(num) for num in y_coord_str.split()]
        # 存储当前y和所有x的距离
        current_y_distances = []
        for x_coord_str in x:
            # 转换当前x坐标为浮点型
            x_coord = [float(num) for num in x_coord_str.split()]
            # 计算各维度差的平方和
            square_sum = 0
            for x_val, y_val in zip(x_coord, y_coord):
                square_sum += (x_val - y_val) ** 2
            # 开根号得到欧氏距离
            distance = math.sqrt(square_sum)
            current_y_distances.append(distance)
        all_distances.append(current_y_distances)
    return all_distances

使用示例

用你给出的测试数据运行:

x = ['1.23568 1.589887', '1.989 1.689']
y = ['2.5689 1.5789', '2.898 2.656']
result = distances_y(x, y)
print(result)

运行后得到的嵌套列表结构如下:

# result[0] 是第一个y和所有x的距离,result[1]是第二个y和所有x的距离
[[1.333239561894217, 0.5860854203953513], [1.9362437702412277, 1.358947018834773]]

如果你需要用命名的方式获取每个y对应的列表,可以转为字典结构:

y_distances = {f'y{i}_list': dist for i, dist in enumerate(result)}
# 直接通过y0_list、y1_list等键取值
print(y_distances['y0_list'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:54:00