我遇到了一个问题,希望有人能给我一个克服它的提示。
我有一个 2D-python-list (83 行和 3 列)。前 2 列是间隔的开始位置和结束位置。第三列是数字索引(例如:9.68)。该列表按第三列反向排序。 我想获得具有最高索引的所有非重叠区间。
以下是排序列表的示例:
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)]
谢谢!
最佳答案
嗯,我对你的代码有一些疑问。自 sort
包含字符串,则此行 append([sort[0][0],sort[0][1]])
你期望什么?
(504, 789),(1024, 1257)
那么存在(1027, 1305)
将被插入到列表中,因为与 (504, 789)
进行比较时它通过了测试.
所以,我做了一些更改,现在它似乎按预期工作:
best_list = [] # Create a list that will store the best intervals
best_list.append(sort[0].rsplit(" ", 1)[0].split()) # 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()
flag = False # <- flag to check the overall overlapping
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))
print(test)
if test:
flag = False
break
flag = True
if flag:
best_list.append([local_start, local_end])
主要思想是检查每个元素,如果它通过了所有重叠测试,则添加它(我的代码的最后一行)。以前没有。
关于Python:在迭代范围时将范围添加到范围列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47865223/