【问题标题】:calculating distance between two coordinate arrays python [duplicate]计算两个坐标数组python之间的距离[重复]
【发布时间】:2018-03-26 03:47:18
【问题描述】:

我在每个数组中有一个包含 4 个坐标的数组

x0 = [1,2,3,4] #x_coordinates
y0 = [1,2,3,4] #y_coordinates

x1 = [11,12,13,14] #x_coordinates
y1 = [11,12,13,14] #y_coordinates

我想求两个坐标之间的距离。

distance = sqrt((x1 - x0)^2 + (y1 - y0)^2)

所以,我试过了

distance = math.sqrt((x1 - x0)**2 + (y1 - y0)**2)

但错误是TypeError: only length-1 arrays can be converted to Python scalars.

仅使用 array_variable 是否可以进行元素明智的操作?还是我必须使用 for 循环对其进行迭代?

我发现这是一个可能的答案,但 numpy 看起来相当复杂。 calculating distance between two numpy arrays

编辑:

尝试了以下

x_dist = pow((x1 - x0), 2)
y_dist = pow((y1 - y0), 2)
dist = x_dist+y_dist
dist=dist**2

【问题讨论】:

  • 你不能在 python 中减去列表。考虑使用numpy 数组。
  • @DyZ :你确定,你不能在 python 中减去ists 吗? x1-x0 看起来完全是真实的声明。
  • 是的,我确定。但是你确定你的 x1 和 x0 是 lists 吗?
  • @DyZ 是的,它是.. print x0 给了我 [413.59921265 412.74182129 411.94470215 411.37411499]。请查看我编辑的答案,它不再给出错误。所以我很困惑为什么它可以工作,当它不可能在 python 中减去列表时。
  • 对不起它的 而不是一个列表!我现在明白了。

标签: python arrays


【解决方案1】:

是的,对于普通的 python 列表,您必须使用循环或理解来按元素执行操作。

使用 numpy 并不复杂,您只需将每个列表包装在 array 中:

from numpy import array, sqrt

x0 = array([1, 2, 3, 4])  # x_coordinates
y0 = array([1, 2, 3, 4])  # y_coordinates

x1 = array([11, 12, 13, 14])  # x_coordinates
y1 = array([11, 12, 13, 14])  # y_coordinates

print(sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2))

下面是如何使用循环理解在普通 Python 中做到这一点:

from math import sqrt

x0_list = [1, 2, 3, 4]  # x_coordinates
y0_list = [1, 2, 3, 4]  # y_coordinates

x1_list = [11, 12, 13, 14]  # x_coordinates
y1_list = [11, 12, 13, 14]  # y_coordinates

print([sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)
       for x0, y0, x1, y1 in zip(x0_list, y0_list, x1_list, y1_list)])

【讨论】:

  • 你能看看我的编辑并告诉我这是不是另一种方法吗?
  • @infoclogged 如果您使用列表,则不。如果您使用其他东西,请告诉我它是否有效。
  • 如何找到 x0 的类型?那我告诉你。但是通过打印 x0 和 x1,它们在我看来确实像一个列表..
  • print(type(x0))。但是您是如何创建它们的呢?
  • 它的 ... dint 知道有这么多数组类型.. 我来自 c++ 世界。对不起。感谢您的回答。它有效。
【解决方案2】:

没有 numpy,这个可以用:

import math

def func(x0,x1,y0,y1):

    distance = []

    for a,b,c,d in zip(x0,x1,y0,y1):
        result = math.sqrt((b - a)**2 + (d - c)**2)
        distance.append(result)

    return distance

x0 = [1,2,3,4] #x_coordinates
y0 = [1,2,3,4] #y_coordinates

x1 = [11,12,13,14] #x_coordinates
y1 = [11,12,13,14] #y_coordinates

print(func(x0, x1, y0, y1))

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 1970-01-01
    • 2020-02-12
    • 2018-06-12
    • 1970-01-01
    • 2017-11-28
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多