I am attempting to implement the solution to a previous SO question
I have a pair of coordinates that I wish to find the closest associated pair of coordinates in a list of coordinates.
This can be achieved by finding the pair with the minimum distance between points:
dist = lambda s,d: (s[0]-d[0])**2+(s[1]-d[1])**2
I have a dictionary, origin:
{u'toid': u'osgb4000000029928750', u'point': [524511.405, 184846.794]}
I have another list containing pairs of coordinates, d_origins:
[(532163.5648939193, 181848.77608212957),(532449.8292416488, 181847.71793660522), (532200.2156880093, 182053.30247829395), (533794.6284605444, 181119.5631480558)]
I then attempt to find the match value by calling the dist lambda function:
match = min((origin[0]['point']),key=partial(dist,d_origins))
print origins, match
however, the output is:
TypeError: 'float' object has no attribute '__getitem__'
The min
function takes a list or iterable. Additionally the ordering can be specified by a function with one argument. That means the function maps an element to a value, which is then compared by the min
function to find the minimum element.
match = min(d_origins, key=lambda p: dist(p, origin['point']))
The lambda expression wraps the dist
function with two arguments to a function with one argument by providing one of the arguments. The new anonymous function compares a coordinate with the specific origin in the lambda expression. Then, the result of the min
function is the closest coordinate to this origin.
Full example:
>>> dist = lambda s,d: (s[0]-d[0])**2+(s[1]-d[1])**2
>>> origin = {'toid': 'osgb4000000029928750', 'point': [524511.405, 184846.794]}
>>> d_origins = [(532163.5648939193, 181848.77608212957),(532449.8292416488, 181847.71793660522), (532200.2156880093, 182053.30247829395), (533794.6284605444, 181119.5631480558)]
>>>
>>> match = min(d_origins, key=lambda p: dist(p, origin['point']))
>>> print(str(match))
(532200.2156880093, 182053.30247829395)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.