下面將找到(歐式)(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