下面将找到(欧式)(x1, y1)
之间的每一个点在p
距离:
In [6]: [math.sqrt((x1-x2)**2+(y1-y2)**2) for x2,y2 in p]
Out[6]: [0.0, 1.0, 1.0, 1.4142135623730951, 1.0, 1.4142135623730951]
如果你只想躺在从(x1, y1)
一定距离内的点,你可以写:
In [8]: [(x2,y2) for x2,y2 in p if math.sqrt((x1-x2)**2+(y1-y2)**2) <= 1.0]
Out[8]: [(0, 0), (1, 0), (0, 1), (0, -1)]
这里,1.0
是所需的半径。
为了把它放在一起:
import math
def filter_points(points, origin, radius=1.0):
x1, y1 = origin
return [(x2,y2) for x2,y2 in points if math.sqrt((x1-x2)**2+(y1-y2)**2) <= radius]
p = [(0, 0), (1, 0), (0, 1), (1, 1), (0, -1), (-1, 1)]
print(filter_points(p, (0, 0), 1.0))
注:值得记住四舍五入的问题:非常接近边界的点可能最终会被误分类。是否重要,以及如何最好地处理这取决于你打算如何处理结果。
当半径为1时,你会得到这个结果。 –
[当你尝试解决这个问题](http://mattgemmell.com/2008/12/08/what-have-you-tried/),解决方案的哪一部分卡住了? – Johnsyweb