我遇到問題並希望任何人都可以給我一個小技巧來克服它。Python:在迭代時將範圍添加到範圍列表
我有一個2D-python-list(83行和3列)。前兩列是間隔的開始和結束位置。第三列是數字索引(例如:9.68)。該列表按第3列進行反向排序。 我想要得到所有與最高索引不重疊的區間。
這裏是排序列表的示例:
504 789 9.68
503 784 9.14
505 791 8.78
499 798 8.73
1024 1257 7.52
1027 1305 7.33
507 847 5.86
這裏是我的嘗試:
# Define a function that test if 2 intervals overlap
def overlap(start1, end1, start2, end2):
return not (end1 < start2 or end2 < start1)
best_list = [] # Create a list that will store the best intervals
best_list.append([sort[0][0],sort[0][1]]) # Append the first interval of the sorted list
# Loop through the sorted list
for line in sort:
local_start, local_end = line.rsplit("\s",1)[0].split()
for i in range(len(best_list)):
best_start = best_list[i][0]
best_end = best_list[i][1]
test = overlap(int(best_start), int(best_end), int(local_start), int(local_end))
if test is False:
best_list.append([local_start, local_end])
我也得到:
best_list = [(504, 789),(1024, 1257),(1027, 1305)]
但我想:
best_list = [(504, 789),(1024, 1257)]
謝謝!
原始列表是怎樣的?值是字符串嗎?如果是,那麼還沒有列。 –
其實,它們是字符串,這就是爲什麼我需要將它們轉換爲整數來進行測試。這是我用包csv中的csv.reader函數創建的一個列表。 –
所以像這樣:'[['504 789 9.68'],['503 784 9.14'],....]'? –