提问人:Tallion 22 提问时间:10/26/2022 最后编辑:wjandreaTallion 22 更新时间:10/26/2022 访问量:49
从给定的嵌套列表中获取最近的嵌套列表
get the nearest nested list from a given nested list
问:
所以我有一个 2 个值和一个多个嵌套值的列表,例如[-82.819309,40.081296]
[[-83.0347849999999, 39.945993],
[-82.957851, 40.060118],
[-82.994303, 40.013227],
[-82.8265609999999, 39.9207779999999],
[-82.9984709999999, 39.887616],
...]
现在我想从嵌套列表中获取列表,其与两个值的差异最小。 类似的东西
>>> getmin([1,2], [[1,1],[1,4],[2,3],[3,2]])
[1,1]
逻辑:
[1,2] - [1,1] = abs(1-1) + abs(2-1) -> 1
[1,2] - [1,4] = abs(1-1) + abs(2-4) -> 2
[1,2] - [2,3] = abs(1-2) + abs(2-3) -> 2
[1,2] - [3,2] = abs(1-3) + abs(2-2) -> 2
有没有办法做到这一点?
答:
2赞
Michael Sohnen
10/26/2022
#1
您可以使用非常简单的代码:
import numpy as np
mylist = [[-83.0347849999999, 39.945993],
[-82.957851, 40.060118],
[-82.994303, 40.013227],
[-82.8265609999999, 39.9207779999999],
[-82.9984709999999, 39.887616],
...]
def item_of_min_norm(target_coordinate):
norms = [np.linalg.norm(np.array(target_coordinate,float)-np.array(item,float), ord=1) for item in mylist]
index_of_minimum = np.argmin(norms)
minimum_item = mylist[index_of_minimum]
return minimum_item
# Use the new function
closest_to_1_1 = item_of_min_norm([1.0,1.0])
但是,如果我能正确猜测您的用例,您可能希望使用 KDTree。 请参阅 https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KDTree.html
评论
numpy
np.ones
np.norm
np.argmin
numpy.norm
numpy.linalg.norm
ord=1