Python : Finding An Item In A List Where A Function Return A Minimum Value?
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.15
Solution 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)
).
Post a Comment for "Python : Finding An Item In A List Where A Function Return A Minimum Value?"