我的資料結構如下:
data=
[
(120,150,150,160,"word1"),
(152,150,170,160,"word2"),
(172,150,200,160,"word3"),
(202,290,240,300,"word4"),
(300,150,350,160,"word5"),
(202,200,240,210,"word6"),
(242,200,260,210,"word7")
]
我想回傳資料中當前串列的第三個數字和下一個專案的第一個數字之間的差異小于 5 并且當前串列項的第四個數字和第四個數字之間的差異小于的任何單詞2 在一個陣列中。然后我想將所有這些陣列附加到主串列中。
所以這將是應用于資料的函式的結果:
final=
[[
(120,150,150,160,"word1"),
(152,150,170,160,"word2"),
(172,150,200,160,"word3")
],
[
(202,200,240,210,"word6"),
(242,200,260,210,"word7")
]]
word4不包括在內,因為 data[2][3]-data[3][3]>2
word5不包括在內,因為 data[3][2]-data[4][0]>2
我目前的嘗試正確處理了 90% 的單詞,但有時會結合不滿足要求的單詞:
temp=[]
final=[]
for i,j in enumerate(data[:-1]):
if(j[2]-data[i 1][0]<5) and (j[3]-data[i 1][3]<2):
if len(temp)<1:
temp.append(j[0:4])
temp.append(data[i 1][0:4])
else:
final.append(temp)
temp=[]
if temp:
final.append(temp)
編輯:這是上述演算法失敗的真實示例:
data=
[
(38.0, 296.7943420410156, 90.86400604248047, 310.7943420410156, 'Contract'),(94.7560043334961, 296.7943420410156, 154.6480102, 310.7943420, 'Summary'),
(250.64453125, 317.38818359375, 266.743530, 325.88818359375, 'This')
]
預期輸出:
final=
[[
(38.0, 296.7943420410156, 90.86400604248047, 310.7943420410156, 'Contract'),(94.7560043334961, 296.7943420410156, 154.6480102, 310.7943420, 'Summary')
]]
實際輸出:
final=
[[
(38.0, 296.7943420410156, 90.86400604248047, 310.7943420410156, 'Contract'),(94.7560043334961, 296.7943420410156, 154.6480102, 310.7943420, 'Summary'),
(250.64453125, 317.38818359375, 266.743530, 325.88818359375, 'This')
]]
uj5u.com熱心網友回復:
您需要比較數字并添加abs,因為差異可能是負數。我還稍微美化了您的代碼:
data = [
(38.0, 296.7943420410156, 90.86400604248047, 310.7943420410156, 'Contract'),
(94.7560043334961, 296.7943420410156, 154.6480102, 310.7943420, 'Summary'),
(250.64453125, 317.38818359375, 266.743530, 325.88818359375, 'This')
]
temp = []
final = []
for index, item in enumerate(data[:-1]):
if abs(item[2] - data[index 1][0]) < 5 and abs(item[3] - data[index 1][3]) < 2:
if len(temp) < 1:
temp.append(item[0:4])
temp.append(data[index 1][0:4])
else:
final.append(temp)
temp = []
if temp:
final.append(temp)
print(final)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/481940.html
