簡體   English   中英

Python:如何僅返回此 if 語句的第一個真值?

[英]Python: How to return only the first true value of this if statement?

如果我有以下代碼包含點 a,b,c,d 並說如果 a/b 與 c/d 相交,那么我們將交點添加到列表中(應該注意,這都在嵌套for 循環和點 c/d 更像 c[i] 和 d[i+1] 是在更大的點值列表中選擇的后續點對)。 所以基本上,a/b 是恆定的,但是 c/d 每次都會改變以測試 a/b 是否與它相交。

此圖像顯示線 a->b(分別為紅色和綠色點),黑色點和棕色線表示由后續點創建的線。 在左圖中,來自 a->b 的線將與兩條棕色線相交,但我只希望下面的代碼返回 true 到橙色圓圈中的一條(最靠近點 a 的一條),然后將 append 返回到 sectlist。 如果只有一個交叉點,我也希望它能夠工作,就像在正確的例子中一樣

這是代碼:

for i in range(400): #number of total points that together create a polygon
    a = (x[0], y[0])
    b = (0, testpoint1)
    #so a line is made from the first value in x,y and testpoint1
    c = (x[i], y[i])
    d = (x[i+1], y[i+1])
    #and subsequent lines are made for every subsequent value in the original list of values
    if intersect_bool(a,b,c,d) == True:
        sectlist.append(intersect_point(a,b,c,d))
    

如果 a/b 只與一對值 c/d 相交,這可以正常工作,但我怎樣才能讓它只返回 True 一次(並且 append 只是第一個相交並繼續腳本)?

編輯:我在代碼中添加了大量內容,因此問題更容易理解+帶有描述的圖像

我不太明白這個問題,但你也許可以使用類似的東西

if any([intersect_bool(a, b, c, d) for c, d in *insert iterable here*])

更新:我已經編輯了我的答案以提供一個例子。

鑒於我仍然不清楚某些點的外觀,我為您創建了一個示例示例,以說明您可以做到這一點的一種方法,我使用了Shapely

from shapely.geometry import Point, MultiPoint, LineString
from shapely.ops import nearest_points

# prepare a sample line and list of points
some_line = LineString([(0, 0), (1, 1), (0,3)])
some_points = [Point(1,1), Point(1,2), Point(1,3)]
some_list = list() 

# Get all intersecting points
for p in some_points:
    if p.intersects(some_line):
        some_list.append(p)

# convert gathered points to a list of destinations
destinations = MultiPoint(some_list)
# Find nearest items to a given origin point
nearest_geoms = nearest_points(some_line, destinations) # nearest_points(origin, destinations)
# print the nearest item
print(nearest_geoms[0])

我希望這有助於回答你的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM