问题: 有人能提出一个更好或更具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 """
这里有一个解决方案。它可能不是很像Python,因为我对Python的经验非常有限,但它很管用。在
其思想是首先按第一项对所有范围对进行排序。这就是
merged.sort()
所做的(它使用连续的元组成员来消除歧义,但这在这里并不重要)。然后我们循环排序后的范围对,只要我们在一堆重叠的范围内,我们就把所有的开始和结束添加到当前集合中。为了知道束流何时结束,我们保持所有射程结束的最大值。一旦一个范围开始超过这个最大值,我们通过将当前集合附加到一个列表来存储它,并开始一个新的集合。最后一个集合必须在循环之后添加到列表中。现在我们有了一个集合列表,我们可以很容易地将其转换为列表列表或成对列表。在不确定您的环境约束,但如果您没有任何约束,您可能需要考虑这个:https://pypi.org/project/intervaltree/ 尤其是
请你澄清一下这个问题好吗。我看到}。},或者其他什么?在
[(0,5), (1,2)]
产生{[(0,5), (1,5)]
会产生什么,[(0, 1), (1, 5), (5, 5)]
,或者仅仅是{相关问题 更多 >
编程相关推荐