Python 点到点列表之间的距离

Python 点到点列表之间的距离,python,Python,我试图计算从点p到列表s中每个点的距离 导入数学 s=[(1,4)、(4,2)、(6,3)] p=(3,7) p0,p1=p dist=[] 对于s中的s0、s1: dist=math.sqrt((p0[0]-p1[0])**2+(s0[1]-s1[1])**2) 距离=距离+1 打印(区) TypeError回溯(最近一次调用) 在里面 3区=[] s0为4,s为s1: ---->5 dist=math.sqrt((p0[0]-p1[0])**2+(s0[1]-s1[1])**2) 6.

我试图计算从点
p
到列表
s
中每个点的距离

导入数学
s=[(1,4)、(4,2)、(6,3)]
p=(3,7)
p0,p1=p
dist=[]
对于s中的s0、s1:
dist=math.sqrt((p0[0]-p1[0])**2+(s0[1]-s1[1])**2)
距离=距离+1
打印(区)

TypeError回溯(最近一次调用)
在里面
3区=[]
s0为4,s为s1:
---->5 dist=math.sqrt((p0[0]-p1[0])**2+(s0[1]-s1[1])**2)
6.
7.
TypeError:“int”对象不可下标
我看到当
p0,p1
are
int
s时,访问该位置被停止。但是在这个场景中,我不知道如何解决这个问题。

dist=math.sqrt((p0[0]-p1[0])**2+(s0[1]-s1[1])**2)

在这里,您正在索引整数

此外,您在计算中犯了错误。应该是:


dist=math.sqrt((p0-s0)**2+(p1-s1)**2)

可能尝试更改此行:

    dist=math.sqrt((p0[0] - p1[0])**2 + (s0[1] - s1[1])**2)
致:


您无意中对数据使用了索引,即使您已将点分隔为
x,y
。此外,您正在覆盖列表而不保存数据。此外,距离公式不正确,它应该是点之间的减法,而不是加法。试试这个:

import math
s= [(1,4),(4,2),(6,3)]
p= (3,7)

p0,p1=p
dist=[]

for s0,s1 in s:
    dist_=math.sqrt((p0 - s0)**2 + (p1 - s1)**2) #Edit this line to [0]s and [1]s
    dist_= dist_+1 #Also change name and/or delete
#    print(dist)
    dist.append(dist_) #Save data to list

如果你想要欧几里德距离,你可以这样做(即使没有
导入数学

结果:

(3,7)(1,4)3.6
(3, 7) (4, 2) 5.1
(3, 7) (6, 3) 5.0
代码中出现的错误是因为对整数使用了索引。就像这样:

>a=3
>>>a[0]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
a[0]
TypeError:“int”对象不可下标

如果所需的是一个距离列表,则可以在一行代码中使用列表:

import math
import pprint

s = [(1,2),(3,4),(-1,1),(6,-7),(0, 6),(-5,-8),(-1,-1),(6,0),(1,-1)]
p = (3,-4)

dists = [math.sqrt((p[0]-s0)**2 + (p[1]-s1)**2) for s0, s1 in s]

pprint.pprint(dists)
这里的另一件事是,我已经从OPs代码中删除了
dist=dist+1
。我不认为这是正确的…为什么每个计算的距离加1

结果:

[6.324555320336759,
 8.0,
 6.4031242374328485,
 4.242640687119285,
 10.44030650891055,
 8.94427190999916,
 5.0,
 5.0,
 3.605551275463989]
array([3.60555128, 5.09901951, 5.])

以防您不受可以使用的包的限制。使用NumPy的实现将更加快速

import numpy as np

s = np.array([(1,4),(4,2),(6,3)])
p = np.array((3,7))

dist = np.linalg.norm(p - s, axis=1)
结果:

[6.324555320336759,
 8.0,
 6.4031242374328485,
 4.242640687119285,
 10.44030650891055,
 8.94427190999916,
 5.0,
 5.0,
 3.605551275463989]
array([3.60555128, 5.09901951, 5.])

期望的输出是什么?您正在索引一个整数,这是不可能的(
p0[0]
)其他人已经解决了您代码中最紧迫的问题。还有一些谜团;什么是
dist=[]
,为什么要用
dist=dist+1
将1添加到计算距离中。您可能只想删除这两行代码。或者你想做更多的事情,比如把每个距离添加到一个列表中,这样你就得到了一个结果,而不是仅仅打印每个距离?@Steve是的,你的右dist=dist+1没有意义。但是dist=[]是必需的,因为我们将结果存储在一个列表中。哈!您通过更新您的答案解决了我对OPs问题的每一个问题。伟大的当我修好一件事时,我发现另外一件事出了问题。lol。检查math.hypot()。使您不必自己实现它,并且在某些恶劣的情况下可能会提供更好的精度。
array([3.60555128, 5.09901951, 5.])