Python:在列表中查找函数返回最小值的项目?

时间:2021-12-20 03:35:43

I've a list of point with coordinates and another point.

我有一个带坐标和另一个点的点列表。

A sample from the list :

列表中的示例:

(45.1531912,5.7184742),(45.1531912,5.7184742),(45.1531113,5.7184544),(45.1525337,5.718298),(45.1525337,5.718298),

A point :

一个点 :

(45.1533837,5.7185242)

A function :

功能:

def dist(point1,point2)
   ....
   return aDistance

Is there a python one liner (list-comprehension ?) to find a point in the list where a given function returns the minimal value for the list ?

是否有一个python one liner(list-comprehension?)来查找列表中给定函数返回列表最小值的点?

1 个解决方案

#1


8  

The min() function takes a key argument already, no need for a list comprehension.

min()函数已经获取了一个关键参数,不需要列表推导。

Let's say you wanted to find the closest point in the list to the origin:

假设您想要找到列表中距离原点最近的点:

min(list_of_points, key=lambda p: distance(p, (0, 0)))

would find it (given a distance() function that calculates the distance between two points).

会找到它(给定一个计算两点之间距离的距离()函数)。

From the documentation:

从文档:

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, min(a,b,c,key=func)).

可选的key参数指定一个单参数排序函数,就像list.sort()一样。键参数(如果提供)必须采用关键字形式(例如,min(a,b,c,key = func))。

#1


8  

The min() function takes a key argument already, no need for a list comprehension.

min()函数已经获取了一个关键参数,不需要列表推导。

Let's say you wanted to find the closest point in the list to the origin:

假设您想要找到列表中距离原点最近的点:

min(list_of_points, key=lambda p: distance(p, (0, 0)))

would find it (given a distance() function that calculates the distance between two points).

会找到它(给定一个计算两点之间距离的距离()函数)。

From the documentation:

从文档:

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, min(a,b,c,key=func)).

可选的key参数指定一个单参数排序函数,就像list.sort()一样。键参数(如果提供)必须采用关键字形式(例如,min(a,b,c,key = func))。