从python中的for循环返回最大或最小的结果

0 python for-loop

假设胸部是两个项目列表的坐标列表.

例如胸部= [[2,4],[4,5],[1,3]]

通过下面的功能,我想要点(x,y)和每个胸部点之间的距离.事实上,这个函数会返回这三个距离,对吧?但我的问题是,如何仅从这三个值中返回最小(或最大)的结果?如果没有创建新的距离列表,有没有办法做到这一点?

def makeMove(board,chest,x,y):

for cx, cy in chests:
    distance = sqrt(abs((x-cx)**2) + abs((y-cy)**2)))
    return distance
Run Code Online (Sandbox Code Playgroud)

Amb*_*ber 7

你可以使用max()min()加上一个生成器表达式......

return max(
    sqrt( abs(x - cx) + abs(y - cy) )
    for cx, cy in chests)
Run Code Online (Sandbox Code Playgroud)

另请注意,作为优化,您可能更愿意这样做(因为if sqrt(x) > sqrt(y),然后x > y)减少sqrt调用次数:

return sqrt(max(
    abs(x - cx) + abs(y - cy)
    for cx, cy in chests))
Run Code Online (Sandbox Code Playgroud)

(另外,你确定你不想平方距离而不是abs()它们吗?正常的距离公式是sqrt((x-x')^2 + (y-y')^2)......)