如何用lambda对元组进行排序

Yve*_*ves 4 python sorting lambda

我有一个元组坐标:

[(1, 2), (3, 2), (1, 4)]
Run Code Online (Sandbox Code Playgroud)

我也有一个协调: (8, 7)

现在我需要根据元组中每个点与单个点之间的距离对上面的元组进行排序.

怎么做sorted()

Cor*_*mer 7

基本上,您可以计算点pt与列表中每个元组之间的欧氏距离.该功能numpy.hypot可以做到这一点,尽管如果你愿意的话,实现自己也是微不足道的.

>>> from numpy import hypot
>>> l = [(1, 2), (3, 2), (1, 4)]
>>> pt = [8,7]
>>> sorted(l, key = lambda i: hypot(i[0]-pt[0], i[1]-pt[1]))
[(3, 2), (1, 4), (1, 2)]
Run Code Online (Sandbox Code Playgroud)