我需要获取我创建的列表并找到最接近的两个点并打印出来.如何比较列表中的每个点?
没有任何需要绘图或任何东西,只需比较点并找到列表中最接近的两个.
import math # 'math' needed for 'sqrt'
# Distance function
def distance(xi,xii,yi,yii):
sq1 = (xi-xii)*(xi-xii)
sq2 = (yi-yii)*(yi-yii)
return math.sqrt(sq1 + sq2)
# Run through input and reorder in [(x, y), (x,y) ...] format
oInput = ["9.5 7.5", "10.2 19.1", "9.7 10.2"] # Original input list (entered by spacing the two points).
mInput = [] # Manipulated list
fList = [] # Final list
for o in oInput:
mInput = o.split()
x,y = float(mInput[0]), float(mInput[1])
fList += [(x, y)] # outputs [(9.5, 7.5), (10.2, 19.1), (9.7, 10.2)]
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 34
重写distance()函数以将两个(x, y)元组作为参数更方便:
def distance(p0, p1):
return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
Run Code Online (Sandbox Code Playgroud)
现在,您想迭代列表中的所有点对fList.该功能iterools.combinations()非常方便:
min_distance = distance(fList[0], fList[1])
for p0, p1 in itertools.combinations(fList, 2):
min_distance = min(min_distance, distance(p0, p1))
Run Code Online (Sandbox Code Playgroud)
另一种方法是定义distance()在单个参数中接受这对点
def distance(points):
p0, p1 = points
return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
Run Code Online (Sandbox Code Playgroud)
并将key参数用于内置min()函数:
min_pair = min(itertools.combinations(fList, 2), key=distance)
min_distance = distance(min_pair)
Run Code Online (Sandbox Code Playgroud)
Jos*_*del 11
我意识到在这个问题上存在库约束,但是为了完整性,如果你N在Nx2 numpy ndarray(2D系统)中有点:
from scipy.spatial.distance import pdist
x = numpy.array([[9.5,7.5],[10.2,19.1],[9.7,10.2]])
mindist = numpy.min(pdist(x))
Run Code Online (Sandbox Code Playgroud)
我总是试图鼓励人们使用numpy/scipy,如果他们正在处理最好存储在数值数组中的数据,并且很高兴知道这些工具可以在那里供将来参考.