Python : Finding an item in a list where a function return a minimum value?

一曲冷凌霜 提交于 2020-01-04 06:25:11

问题


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 ?


回答1:


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

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)).



来源:https://stackoverflow.com/questions/22744237/python-finding-an-item-in-a-list-where-a-function-return-a-minimum-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!