Skip to main content
 首页 » 编程设计

列表中 float 的 Python 成员资格

2024年09月07日9虾米姐

假设我有一个 points 形式的 (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!