我有行串列,每一行都是這樣的串列
[firstpoint, secondpoint]
例如,我有 4 行這樣的:
listoflines = [[0,2],[1,3],[2,5],[6,7]]
因此,當您看到某些線具有相互段時,如果它們具有相互段,我想要加入它們,因此結果將是:
newlistoflines = [[0,5],[6,7]]
我嘗試的是使用一個函式將它們相互比較并回圈遍歷我的行串列,但我的結果有問題:
def JOINLINES(line1, line2):
x1 = line1[0]
x2 = line1[1]
x3 = line2[0]
x4 = line2[1]
if x2 < x3:
result = (x1, x2), (x3, x4)
else:
result = (min(x1, x2, x3, x4), max(x1, x2, x3, x4))
return result
newbeamlist = []
for i in range(1, len(beams)):
newbeamlist.append(JOINLINES(beams[i - 1], beams[i]))
輸出 = [(0, 3), (1, 5), ((2, 5), (6, 7))]
uj5u.com熱心網友回復:
您的解決方案是附加 JOINLINES 函式的結果。
它沒有考慮下一個專案也可能是一個相互部分。
試試這個。我已經假設了一些事情。
# assuming that the items in the list are ordered according to the first item in each sublist.
# This will enable us to find mutual segments (overlaps) easily
# if the list is not sorted, then we can sort it using the first item in each sublist item
li = [[0,2],[1,3],[2,5],[6,7], [10,11],[7,9]]
# sorting using the first item in each sublist item
li.sort(key=lambda x: x[0])
# out: [[0,5],[6,7]]
newli= []
left_prev = li[0][0]
right_prev = li[0][1]
for i in range(1,len(li)):
left_current = li[i][0]
right_current = li[i][1]
if left_current <= right_prev:
# mutual segment (overlap) found
right_prev = right_current
continue
else:
# no mutual segment(overlap), append the previous to the new list
newli.append([left_prev, right_prev])
left_prev = left_current
right_prev = right_current
# appending the last item
newli.append([left_prev, right_prev])
print(newli) # [[0, 5], [6, 9], [10, 11]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/476780.html
