簡體   English   中英

點到點列表之間的距離

[英]Distance between point to list of points

我正在嘗試計算從點p到列表s每個點的距離。

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[0] - p1[0])**2 + (s0[1] - s1[1])**2)
    dist= dist+1
    print(dist)

TypeError                                 Traceback (most recent call last)
<ipython-input-7-77e000c3374a> in <module>
      3 dist=[]
      4 for s0,s1 in s:
----> 5    dist=math.sqrt((p0[0] - p1[0])**2 + (s0[1] - s1[1])**2)
      6 
      7 

TypeError: 'int' object is not subscriptable

我看到訪問該位置已停止,因為p0,p1int s。 但在這種情況下,我不知道如何解決這個問題。

即使您已經將點分成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

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

在這里,您正在索引整數。

此外,您在計算中犯了錯誤 它應該是:

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

如果需要的是距離列表,則可以在具有列表理解的單行代碼中完成:

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]

也許嘗試改變這一行:

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

到:

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

如果你想要歐幾里得距離,你可以做這樣的事情(即使沒有import math

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

for point in s:
    sum_ = sum((p[i] - point[i]) ** 2 for i in range(len(p)))
    distance = sum_ ** (1 / 2)  # take the square root, the same thing as math.sqrt()
    print(p, point, round(distance, 1))

結果:

(3, 7) (1, 4) 3.6
(3, 7) (4, 2) 5.1
(3, 7) (6, 3) 5.0

您在代碼中遇到的錯誤是因為您對整數使用了索引。 就像這樣做:

>>> a = 3
>>> a[0]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    a[0]
TypeError: 'int' object is not subscriptable

如果您不受可以使用的軟件包的限制。 使用 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)

結果:

array([3.60555128, 5.09901951, 5.])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM