![](/img/trans.png)
[英]How can I find the nearest distance between points in a 2D array and a 3D matrix grid?
[英]How to find the distance between two elements in a 2D array
假設您有網格:
list = [[-,O,-,-,O,-,],
[O,-,-,-,-,O],
[O,O,-,-,X,-],
[-,-,O,-,-,-]]
您將如何獲得距離 X 3 以內的所有 O 的坐標? 從我在其他答案中看到的情況來看,使用scipy.spatial.KDTree.query_ball_point似乎是一種常見的方法,但我無法弄清楚如何使其適應我的用例。 我有一個可能的想法是存儲列表的每個坐標,例如coords=[[0,0],[0,1]...]
然后使用 scipy 方法並傳入 X 的坐標和搜索距離。 然后,一旦我收到可能的坐標列表,我就會遍歷列表並檢查哪些坐標等於 O。但是,我想知道是否可以使用更有效或更優化的解決方案。 任何幫助將不勝感激。
你不需要用 Scipy 把它弄得太復雜。這個問題可以很容易地通過數學的幫助來解決。
圓內坐標方程為x^2 + y^2 <= Radius^2
,所以只需檢查圓內坐標即可。
list = [[-,O,-,-,O,-,],
[O,-,-,-,-,O],
[O,O,-,-,X,-],
[-,-,O,-,-,-]]
X_coor = #Coordinate of X, in this case y = 2, x = 4
d = #Maximum distance from X in this case d = 3
total = 0
O_coor = [] #Store coordinate of all O near X
for y in range(max(0, X_coor.y - d), min(list.length - 1, X_coor.y + d)):
for x in range(max(0, X_coor.x - sqrt(d**2 - (y - X_coor.y)**2)), min(list.length - 1, X_coor.x + sqrt(d**2 - (y - X_coor.y)**2))):
if list[y][x] == "O":
total++
O_coor.append([x, y])
print(total)
print(O_coor)
代碼很長,不懂的地方可以問我。
注意:此解決方案僅檢查圓圈區域中的坐標而不是整個列表,因此即使您的列表很大,這仍然非常快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.