Вы можете сделать это так, используя эту функцию клавиш с sorted()
вместо min()
:
from math import cos, asin, sqrt
from pprint import pformat
from textwrap import indent
A = [{'lat': 40.2877, 'lon': -94.7913},
{'lat': 40.7171, 'lon': -73.9664},
{'lat': 32.7052, 'lon': -117.1897},
{'lat': 33.2388, 'lon': -115.5045}]
B = [{'lat' :47.7351, 'lon' : -117.3705},
{'lat' :41.6422, 'lon' : -71.1706}]
def distance(lat1, lon1, lat2, lon2):
p = 0.017453292519943295 # Pi / 180
a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2
return 12742 * asin(sqrt(a))
def nearest(N, data, pt2):
""" Return the nearest N points in data to pt2. """
return sorted(data, key=
lambda pt1: distance(pt2['lat'], pt2['lon'], pt1['lat'], pt1['lon']))[:N]
for item in B:
print(item, '->')
print(indent(pformat(nearest(3, A, item)), ' '))
Выход:
{'lat': 47.7351, 'lon': -117.3705} ->
[{'lat': 33.2388, 'lon': -115.5045},
{'lat': 32.7052, 'lon': -117.1897},
{'lat': 40.2877, 'lon': -94.7913}]
{'lat': 41.6422, 'lon': -71.1706} ->
[{'lat': 40.7171, 'lon': -73.9664},
{'lat': 40.2877, 'lon': -94.7913},
{'lat': 33.2388, 'lon': -115.5045}]