2017-08-13 42 views
1

为什么验证码:如何使这个lambda在Python3中正确工作?

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运行呢?

我试图自己修复它,但我仍然没有得到它...有人可以帮助解决它吗?

+0

还好,好像你不认为这是一个重复,并使用重复的,你解决不了,所以我重新提出了这个问题。当我发现其他Q + A时,我已经发布了一个答案(现在提交),我认为它会是一个合适的副本(但没有人是完美的,对吗?)。对不便之处,我会在几分钟内删除我的评论。 :) – MSeifert

+0

你可以标记为重复或删除,你帮助我的主要事情。为此我感谢你。 –

回答

1

您不能在Python-3.x中解开lambda的参数。虽然它们仍然可以接受多个参数(即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))