简体   繁体   中英

Is there a more pythonic way to find the point in a list which is closest to another point?

I have a list of 2d points, and would like to find the one which is closest to a given point. The code (get_closest_point()) below does what I want. But is there a nicer way to do this in python?

class Circle(object):
    def __init__(self, pos):
        self.position = pos


class Point(object):
    ..
    def compute_distance_to(self, p)
        ..

class SomeClient(object):
    ..

    def get_closest_point(self, points, p1):
        closest = (None, float(sys.maxint))
        for p2 in points:
            distance = p2.compute_distance_to(p1) 
            if distance < closest[1]:
                closest = (p2, distance)

        return closest[0]

    def get_closest_circle(self, circles, p1):
        closest = (None, float(sys.maxint))
        for c in circles:
            distance = c.position.compute_distance_to(p1) 
            if distance < closest[1]:
                closest = (c, distance)

        return closest[0]

You can use the key argument to the min() function:

Edit: after some consideration, this should be a method of your Point class, and i'll fix some other obvious deficiencies:

class Point(object):
    def get_closest_point(self, points):
        return min(points, key=self.compute_distance_to)

or, to do this with a more elaborate case, say a list of instances with a loc attribute,

min(items, key= lambda item: p1.compute_distance_to(item.loc))

and so on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM