python - 查找与最接近的提供的数字配对匹配的索引

标签 python arrays list indexing min

我在 Python 中有三个单独的列表,它们都非常大。一项规定是列表不能按照当前显示方式重新排序。每个列表的外观片段如下:

lats = [40.92322342,40.92322342,40.92322342,40.92322342,40.92322342] 长度 = [-74.32176109,-74.29518277,-74.26860445,-74.24202613,-74.21544781] 数据 = [19,19,19,17,18]

我希望提供纬度和经度配对,并希望返回与所提供的纬度和经度最接近的data列表的索引号和相应值。

例如,配对 40.9254, -74.2765 将返回相应的索引号,这将是上面提供的列表片段中的第三组值。

使用this example ,我已经能够按单个列表对此搜索进行分区并返回相应的索引号。然而,索引号不同。

代码:

min(枚举(lats),key=lambda x:abs(x[1]-40.9254)) min(枚举(lons),key=lambda x:abs(x[1]-(-74.2765)))

索引号,40.92322342 与上面不同的索引号,-74.26860445

有什么有效的方法可以解决这个问题吗?

最佳答案

您可以首先使用 sqrt((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2) 找到两点之间的 euclidean distance ,然后将其与 min() 结合作为 key 来找到最近的点。

from math import sqrt

lats = [40.92322342,40.92322342,40.92322342,40.92322342,40.92322342]
lons = [-74.32176109,-74.29518277,-74.26860445,-74.24202613,-74.21544781]

def euclidean_distance(x, y):
    return sqrt((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2)

def find_closest_point(data, point):
    # create (point, index) pairs
    indices = ((e, i) for i, e in enumerate(data))

    # find smallest point, and only return the index
    return min(indices, key=lambda p: euclidean_distance(p[0], point))[1]

print(find_closest_point(zip(lats, lons), (40.9254, -74.2765)))

返回第三对坐标(索引从0开始):

2

注意:您可以在元组列表中包含 latslons,然后就不需要在函数中调用 zip()

关于python - 查找与最接近的提供的数字配对匹配的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58581485/

相关文章:

python - 如何获取图像的类型(RGB 或 GREY)

java - 如何创建线程(素数和ArrayList)?

.NET 2.0 中的 C# List<T>.ConvertAll

python - 如何初始化先验未知数量的列表

python - 在 Ubuntu Python 2.7 中读取 os.system() 命令的输出

python - 不变的变量,即使它发生变化

python - matplotlib 基线倾斜的 3d 多边形图

arrays - 如何在子文档的每个字段中搜索

Python 两个数组,获取半径内的所有点

ruby - 如何在 Ruby 中选择给定范围内的数组元素?