Skip to main content
 首页 » 编程设计

python之如何在 python 的给定列表中获取彼此最近的点

2025年01月19日9langtianya

from math import hypot 
 
p = [ (0,0),(1,1),(2,3),(4,5)] 
def dist(p1,p2): 
    x1,y1= p1 
    x2,y2= p2 
    return hypot(x2-x1,y2-y1) 
 
from itertools import combinations 
 
distances = [dist(*pair) for pair in combinations( p,2)] 

在这一步之后我不知道该怎么做了..

请您参考如下方法:

尝试构建(pair, dist)键值元组的字典。
然后找到距离值最小的元组。

import operator as op 
 
 
pair_distances = {pair: dist(*pair) for pair in combinations(p, 2)} 
min(pair_distances.items(), key=op.itemgetter(1)) 
#(((0, 0), (1, 1)), 1.4142135623730951)