为什么这段代码:
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))
抛出如下错误:
Tuple parameter unpacking is not supported in python 3
和
SyntaxError: invalid syntax
当我在 Python 3.6 上运行它时?
我试图自己修复它,但我还是不明白...有人可以帮忙修复吗?
请您参考如下方法:
您无法解压 lambda 的参数在 python-3.x 中。虽然他们仍然可以接受多个参数(即 lambda x, y: x+y ),但您不能再解压一个参数(即 lambda (x, y): x+y )。
最简单的解决方案是只索引“一个参数”而不是使用解包:
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))
