我遇到了一个问题,希望有人能给我一个克服它的建议。你知道吗
我有一个2dpython列表(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,并且已经有一个列表,其中
[(start, stop, index), ....]
为[(int, int, float), ...]
,那么您可以按以下方式对其排序:这意味着您按第三个位置排序,并按从最大到最小的相反顺序返回结果
然后使用上述函数,您将获得所需的结果。对于提供的代码段,您将获得
[(504, 789, 9.68), (1024, 1257, 7.52)]
。我在这里使用一个事实,即可以使用1 in range(0, 10)
,它将返回True
。虽然这是一个幼稚的实现,但您可以将其作为一个起点。如果只想返回开始和停止请将返回行替换为return [i[:2] for i in result]
。你知道吗注意:我还想补充一点,您的代码有一个逻辑错误。您在每次比较之后都会做出决定,但必须在与您的
best_list
中已经存在的所有元素进行比较之后做出决定。这就是为什么(504, 789)
和(1027, 1305)
通过了测试,但不应该通过。我希望这张纸条能对你有所帮助。你知道吗嗯,我对你的密码有点疑问。既然
sort
包含字符串,那么这一行append([sort[0][0],sort[0][1]])
会做什么呢?你知道吗总之,主要的问题是,当列表中存在多个元素时,只要其中一个元素通过重叠测试就足以添加到列表中(而不是您想要的)。E、 当两个
(504, 789),(1024, 1257)
都存在时,(1027, 1305)
将被插入到列表中,因为与(504, 789)
比较时它通过了测试。你知道吗所以,我做了一些改变,现在它似乎像预期的那样工作:
主要思想是检查每个元素,如果它通过了所有重叠的测试,那么添加它(我代码的最后一行)。以前没有。你知道吗
相关问题 更多 >
编程相关推荐