Reputation: 61
Why does this code:
import math
def nearest_location(locations, my_location):
return min(enumerate(locations), key=lambda (_, (x, y)): math.hypot(x - my_location[0], y - my_location[1]))
locations = [(41.56569, 60.60677), (41.561865, 60.602895), (41.566474, 60.605544), (41.55561, 60.63101), (41.564171, 60.604020)]
my_location = (41.565550, 60.607537)
print(nearest_location(locations, my_location))
throw errors like:
Tuple parameter unpacking is not supported in python 3
and
SyntaxError: invalid syntax
When i run it on Python 3.6?
I tried to fix it myself, but I still do not get it... Can somebody help to fix it?
Upvotes: 2
Views: 262
Reputation: 152667
You can't unpack the arguments for lambda
in python-3.x. While they can still accept multiple arguments (i.e. lambda x, y: x+y
) you can't unpack one argument anymore (i.e. lambda (x, y): x+y
).
The simplest solution would be to just index the "one argument" instead of using unpacking:
import math
def nearest_location(locations, my_location):
return min(enumerate(locations), key=lambda x: math.hypot(x[1][0] - my_location[0], x[1][1] - my_location[1]))
locations = [(41.56569, 60.60677), (41.561865, 60.602895), (41.566474, 60.605544), (41.55561, 60.63101), (41.564171, 60.604020)]
my_location = (41.565550, 60.607537)
print(nearest_location(locations, my_location))
# (0, (41.56569, 60.60677))
Upvotes: 1