Python 计算两个坐标数组之间的距离
我有一个数组,每个数组中有4个坐标Python 计算两个坐标数组之间的距离,python,arrays,Python,Arrays,我有一个数组,每个数组中有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 +
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:只有长度为1的数组才能转换为Python标量。
仅仅使用array_变量不可能执行元素操作吗?或者我必须使用for循环来迭代它吗
我发现这是一个可能的答案,但看起来与numpy相当复杂。
编辑:
尝试了以下方法
x_dist = pow((x1 - x0), 2)
y_dist = pow((y1 - y0), 2)
dist = x_dist+y_dist
dist=dist**2
是的,对于简单的python列表,您必须使用循环或理解来按元素进行操作 numpy并不复杂,您只需将每个列表包装在一个
数组中即可:
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)])
如果没有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))
在python中不能减去列表。考虑使用<代码> NoMPy < /Cord>数组。@ Dyz:你确定,你不能用Python减去ISRIST吗?x1-x0看起来像是一个完全真实的陈述。是的,我确信。但是你确定你的x1和x0是列表吗?@DyZ是的,它是。。打印x0给了我[413.59921265 412.74182129 411.94470215 411.37411499]。请看我编辑的答案,它不再给出错误。所以我很困惑为什么它能工作,而在python中却不能减去列表。对不起,它不是列表!!我现在知道了。你能看看我的编辑并告诉我这是不是另一种方法吗?@infoclocked如果你使用列表,则不是。如果你使用其他方法,则告诉我它是否有效。我如何找到x0的类型?那我就告诉你。但是通过打印x0和x1,它们在我看来确实像一个列表。print(type(x0))
。但是你是怎么创造它们的呢?它。。。我不知道有这么多数组类型。。我来自C++世界。很抱歉谢谢你的回答。它起作用了。