如何将重叠范围“联合”到非重叠范围?

2024-10-03 02:44:42 发布

您现在位置:Python中文网/ 问答频道 /正文

问题: 有人能提出一个更好或更具Python式的方法,将重叠范围对减少到非重叠范围对吗?在

背景: 我有一个表示起始和结束对的元组列表。我试图基本上完成所有起始-结束对的联合。输入开始-结束对具有重叠值,并且输出应该表示没有任何重叠的输入开始-结束对。在

下面的代码很接近,但是错误的,因为它输出了一个不在输入中的额外范围(我也意识到它不是很好,为什么它错了)。有谁能提出一个更好的方法,或者一些我忽略了的内置函数?在

为这个基本问题道歉。 谢谢你的帮助!在

##create example data
pairA =[(0,5),(10,12)]
pairB =[(1,2),(11,15)]
pairC =[(1,4),(10,12),(15,17)]

#combine the lists to one list
#ultimately may have n number of lists and felt it would be easier to
merged = pairA + pairB +pairC
# produce union of list * unpacks the arguments of a list
listUnion= sorted(set().union(*merged))

#this is the piece of code I am looking at improving
#it creates new start end pairs based on the union
lastElement =listUnion[-1]
outList=[]

for item in listUnion:
    #create start end pair from value i and i+1
    if item != lastElement:
        outList.append((item,listUnion[listUnion.index(item)+1]))
    else:
        #last element of the list, becomes the last element of list pair
        #it can be ignored
        pass
print outList 
"""output: [(0, 1), (1, 2), (2,4), (4, 5), (5, 10), (10, 11), (11, 12), (12, 15), (15, 
17)]
correct output: would not have (5,10) as there is no overlap here in the input """

编辑:添加了问题的可视化表示enter image description here


Tags: oftheto方法createititemlists
3条回答

这里有一个解决方案。它可能不是很像Python,因为我对Python的经验非常有限,但它很管用。在

pairs_a = [(0, 5), (10, 12)]
pairs_b = [(1, 2), (11, 15)]
pairs_c = [(1, 4), (10, 12), (15, 17)]

merged = pairs_a + pairs_b + pairs_c
merged.sort()

set_list = []
cur_set = set()
cur_max = merged[0][1]
for pair in merged:
    p0, p1 = pair
    if cur_max < p0:
        set_list.append(cur_set)
        cur_set = set()
    cur_set.add(p0)
    cur_set.add(p1)
    if cur_max < p1:
        cur_max = p1
set_list.append(cur_set)

out_list = []
for my_set in set_list:
    my_list = sorted(my_set)
    p0 = my_list[0]
    for p1 in my_list[1:]:
        out_list.append((p0, p1))
        p0 = p1

# more pythonic but less readable in spite of indentation efforts:
# out_list = [pair
#             for zipped in [zip(list[:-1], list[1:])
#                            for list in [sorted(set)
#                                         for set in set_list]]
#                 for pair in zipped]

# alternate ending:
# out_list = [sorted(set) for set in set_list]

print(out_list)

其思想是首先按第一项对所有范围对进行排序。这就是merged.sort()所做的(它使用连续的元组成员来消除歧义,但这在这里并不重要)。然后我们循环排序后的范围对,只要我们在一堆重叠的范围内,我们就把所有的开始和结束添加到当前集合中。为了知道束流何时结束,我们保持所有射程结束的最大值。一旦一个范围开始超过这个最大值,我们通过将当前集合附加到一个列表来存储它,并开始一个新的集合。最后一个集合必须在循环之后添加到列表中。现在我们有了一个集合列表,我们可以很容易地将其转换为列表列表或成对列表。在

不确定您的环境约束,但如果您没有任何约束,您可能需要考虑这个:https://pypi.org/project/intervaltree/ 尤其是

result_tree = tree.union(iterable)

请你澄清一下这个问题好吗。我看到[(0,5), (1,2)]产生{}。[(0,5), (1,5)]会产生什么,[(0, 1), (1, 5), (5, 5)],或者仅仅是{},或者其他什么?在

相关问题 更多 >