[英]How can i get the closest distance between a tuple and a list of tuples?
I want to find the tuple inside a list that is closest to my given tuple.我想在最接近给定元组的列表中找到元组。
i have a list of coordinates and a point and i need to find the item in the list that is closest to my point.我有一个坐标列表和一个点,我需要在列表中找到最接近我的点的项目。
something like this:像这样的东西:
cords = [(455, 12), (188, 90), (74, 366), (10,10)]
point = (18, 448)
for c in cords:
dst = distance.euclidean(cords[c], point)
Output = closest distance
I tried using scipy.spatial.distance.euclidean
but this gives the error:我尝试使用
scipy.spatial.distance.euclidean
但这给出了错误:
TypeError: list indices must be integers or slices, not tuple
TypeError:列表索引必须是整数或切片,而不是元组
Python min
allows to specify a single-argument function that returns a value (the " key
") and it will return the element that minimizes it. Python
min
允许指定单个参数 function 返回一个值(“ key
”),它将返回最小化它的元素。
min(cords, key=lambda c : distance.euclidean(c, point))
c
is the tuple in the list of coords, it's not the index, so use it instead of cords[c]
, you can also use min
with a generator expression to get what you want: c
是坐标列表中的元组,它不是索引,所以用它代替cords[c]
,你也可以使用min
和生成器表达式来得到你想要的:
from scipy.spatial.distance import euclidean
cords = [(455, 12), (188, 90), (74, 366), (10, 10)]
point = (18, 448)
closest_dst = min(euclidean(c, point) for c in cords)
print(closest_dst)
Output: Output:
99.29753269845128
Try for c in range(len(cords))
.尝试
for c in range(len(cords))
。 As you are, you are taking elements of list into c
, not indexes.正如您一样,您将列表元素放入
c
,而不是索引。
You are passing it the object c as an index.您将 object c 作为索引传递给它。 You could do it using enumerate if you want to use the index or just do it the pythonic way:
如果你想使用索引或者只是使用 pythonic 方式,你可以使用 enumerate 来做到这一点:
cords = [(455, 12), (188, 90), (74, 366), (10,10)]
point = (18, 448)
for c in cords:
dst = distance.euclidean(c, point)
You should save the distances and find the minimum as well.您应该保存距离并找到最小值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.