Python返回列表中距离最小的点

背景

常常需要用函数对列表进行遍历,找到运算结果最小的值。
例如已只一个点和一个点集,返回集合中距离目标点最近的一个。

传统方式

生成一个新列表储存计算结果
用min函数获取最小值,配合index方法查出下标

import numpy as np
set = [np.array([0,1]) , np.array([1,1]) , np.array([1,0])]
point = np.array([0,0])
dist = lambda x: np.linalg.norm(x - point)
result = [dist(x) for x in set]
idx = result.index(min(result))
match = set[idx]

优化方式

直接对min函数传入key参数,结果直接返回列表中的结果最小的元素

import numpy as np
set = [np.array([0,1]) , np.array([1,1]) , np.array([1,0])]
point = np.array([0,0])
dist = lambda x: np.linalg.norm(x - point)
match = min(set, key = dist)
原文地址:https://www.cnblogs.com/azureology/p/13790665.html