假设我有一个 点
形式的元组列表,其形式为 (x, y)
,其中包含 x
和 y
> float 。检查点 (v,w)
是否靠近(欧几里得距离小于某个 epsilon)到 points
中的某个点的最 Pythonic 方法是什么?
(当然,最简单的方法是使用 for 循环来查找。)
我主要想知道 python 3 的情况,但作为引用,python 2 的答案也很好。使用开源库的答案也是可以接受的。
最佳答案
就我个人而言,我会这样做:
#given GIVEN_POINT, MAX_DISTANCE and POINTS
from math import sqrt
print(list(map(lambda e: e[0],filter(lambda x: x[1]<=MAX_DISTANCE, map(lambda p: (p,sqrt((p[0]-GIVEN_POINT[0])**2+(p[1]-GIVEN_POINT[1])**2)),POINTS)))))
说明:
from math import sqrt
#given GIVEN_POINT, MAX_DISTANCE and POINTS
distance=lambda p: sqrt((p[0]-GIVEN_POINT[0])**2+(p[1]-GIVEN_POINT[1])**2)
#(the Euclidean distance from p to GIVEN_POINT where P is a point like (x,y))
point_distance = lambda p: (p,distance(p))
#map store the distance along with each point
points_n_distances = map(point_distance,POINTS)
#Now we have something like [((x1,y1),d1),((x2,y2),d2)...] in a map
close = lambda p: p[1]<=MAX_DISTANCE
closer_points = filter(close,points_n_distances)
#We do a filter based on the distances
to_point = lambda p: p[0]
filtered=map(to_point,closer_points)
#we remove the extra bit of data
#now filtered contains all the (x,y) points which are maximum of a MAX_DISTANCE far from GIVEN_POINT
不要忘记filtered
仍然是一个map
!
关于Python 列表中浮点的成员资格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48873722/