假設我有一個這樣的 Python 腳本
import numpy as np
positions = np.array([[2.5, 8], [3, 10], [0, 5], [1, 5]])
x = positions[:, 0]
y = positions[:, 1]
def isInside(circle_x, circle_y, rad, x, y):
return ((x - circle_x) ** 2 (y - circle_y) ** 2) <= rad ** 2
circle_x = 0;
circle_y = 5;
rad = 2;
for is_inside in isInside(circle_x, circle_y, rad, x, y):
print ("Inside" if is_inside else "Outside")
我現在還想為每個“內部”或“外部”列印相應的 x 和 y 坐標。這應該看起來像這樣
[2.5, 8] Outside, [3, 10] Outside, [0, 5] Inside, [1, 5] Inside
我怎樣才能做到這一點?誰能幫我嗎?
uj5u.com熱心網友回復:
如果您有興趣獲取 x,y 坐標以及檢查該區域的內部或外部,您可以更改您的函式以回傳一個包含 3 個值的元組:x,y, boolean. 我已經編輯了您的代碼并提出了以下代碼:
import numpy as np
positions = np.array([[2.5, 8], [3, 10], [0, 5], [1, 5]])
x = positions[:, 0]
y = positions[:, 1]
def isInside(circle_x, circle_y, rad, x, y):
return (x,y,((x - circle_x) ** 2 (y - circle_y) ** 2) <= rad ** 2)
circle_x = 0;
circle_y = 5;
rad = 2;
is_inside = isInside(circle_x, circle_y, rad, x, y)
output = ""
for index in range(len(is_inside[2])):
output = "[{x}, {y}] Inside,".format(x=is_inside[0][index], y=is_inside[1][index]) if is_inside[2][index] else "[{x}, {y}] Outside,".format(x=is_inside[0][index], y=is_inside[1][index])
print(output.strip(","))
輸出
[2.5, 8.0] Outside,[3.0, 10.0] Outside,[0.0, 5.0] Inside,[1.0, 5.0] Inside
附注:您可以使用shapely模塊來處理地理空間結構。在這個模塊中,您可以使用函式檢查一個點(用坐標定義)是否在一個區域(定義為多邊形)中within。
uj5u.com熱心網友回復:
import numpy as np
positions = np.array([[2.5, 8], [3, 10], [0, 5], [1, 5]])
circle_centre = np.array((0, 5))
rad = 2
print(*(f"[{x}, {y}] {('Outside', 'Inside')[is_inside]}"
for x, y, is_inside in zip(*np.transpose(positions), ((positions - circle_centre) ** 2).sum(1) <= rad ** 2)),
sep=", ")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433836.html
標籤:Python python-3.x 麻木的 numpy-ndarray
