Python:在迭代范围时将范围添加到范围列表中

标签 python list range intervals overlap

我遇到了一个问题,希望有人能给我一个克服它的提示。

我有一个 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/

相关文章:

python - setup.py 中 entry_points/console_scripts 和脚本之间的区别?

python - 有没有一种快速/最佳的方法来获取特定键的唯一值列表?

python - 将列表拆分为单独的列表 [Python]

ruby - 是否可以使用范围作为 Ruby 中散列的键?

python - python 程序如何运行另一个 python 程序,就好像它是从单独的 SSH 终端运行一样?

python - Matplotlib plt.xlabel() 与 ax.set_xlabel()

arrays - 作业中的 Perl 'context'

python - 返回列表列表中特定符号的位置

SQLite 循环语句?

css - 如何将 styleName (css) 放在 ui.xml 到 HTML5 输入元素(范围)