我需要把我创建的列表,找到最接近的两点,然后打印出来。我如何比较列表中的每一点?
不需要绘图或其他任何东西,只需比较点并在列表中找到最接近的两个点。
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)]
我知道这个问题有库约束,但是为了完整起见,如果在Nx2 numpy ndarray(2D系统)中有
N
点:我总是鼓励人们使用numpy/scipy,如果他们处理的数据最好存储在一个数字数组中,并且很好地知道这些工具是为了将来的参考。
更方便的是重写
distance()
函数,将两个(x, y)
元组作为参数:现在您要遍历列表中的所有点对
fList
。函数iterools.combinations()
对此很方便:另一种方法是定义
distance()
以接受单个参数中的点对并将
key
参数用于内置的min()
函数:注意,
math.sqrt
函数既慢又不必要。尝试比较距离平方以加快速度(排序距离与距离平方将始终产生相同的顺序):相关问题 更多 >
编程相关推荐