Python:最近的坐标?

Python:最近的坐标?,python,Python,我需要一个函数的帮助,该函数从最接近某个点的坐标列表中返回坐标。例如:closest9,2,{0,0,10,0,10,10}返回10,0 这是你能做到的一种方法 如果您已经编写了dist方法,那么这是一种稍微简单的方法 def closest(p0,otherPoints): def distTo(p): def _inner(other): return dist(p,other) return inner return

我需要一个函数的帮助,该函数从最接近某个点的坐标列表中返回坐标。例如:closest9,2,{0,0,10,0,10,10}返回10,0

这是你能做到的一种方法

如果您已经编写了dist方法,那么这是一种稍微简单的方法

def closest(p0,otherPoints):
    def distTo(p):
        def _inner(other):
            return dist(p,other)
        return inner
    return min(otherPoints,key=distTo(p0))
甚至更简单

def closest(p0,otherPoints):
    return min(otherPoints,key=lambda x:dist(p0,x))
如果我的数学没有错的话


我使用的是

您到底需要什么帮助?计算从初始点到所有其他点的Euqliden距离,并找到最小距离。1。你需要知道如何计算两点之间的差值。2.比较每一个,得到最小的。到目前为止,你试过什么?或者甚至是距离平方,因为它成本更低,你不关心实际距离,只关心相对距离。如果你需要帮助计算两点之间的距离,请查看此项。我仍然对lambdas感到困惑,你的“最近”函数真的让我感到困惑。你能解释一下吗?我应该提出一个新问题吗?开始聊天?狡辩:你应该有腹肌而不是漂浮在这里;abs已经为abs1j==1做了正确的事情,但是float1j引发了一个类型错误。。。修正:P更多,因为它总是正的,因为它代表向量强度或其他:P
def closest(p0,otherPoints):
    return min(otherPoints,key=lambda x:dist(p0,x))
from math import sqrt

def euqli_dist(p, q, squared=False):
    # Calculates the euclidean distance, the "ordinary" distance between two
    # points
    # 
    # The standard Euclidean distance can be squared in order to place
    # progressively greater weight on objects that are farther apart. This
    # frequently used in optimization problems in which distances only have
    # to be compared.
    if squared:
        return ((p[0] - q[0]) ** 2) + ((p[1] - q[1]) ** 2)
    else:
        return sqrt(((p[0] - q[0]) ** 2) + ((p[1] - q[1]) ** 2))

def closest(cur_pos, positions):
    low_dist = float('inf')
    closest_pos = None
    for pos in positions:
        dist = euqli_dist(cur_pos,pos)
        if dist < low_dist:
            low_dist = dist
            closest_pos = pos
    return closest_pos

print closest((9, 2), {(0, 0), (10, 0), (10, 10)})
(10, 0)