【发布时间】:2018-10-18 18:01:08
【问题描述】:
问题: 任何人都可以提出更好或更 Pythonic 的方法,将重叠范围对减少为非重叠范围对吗?
背景: 我有一个表示开始和结束对的元组列表。我试图从本质上完成所有开始结束对的联合。输入起始端对具有重叠值,输出应代表输入起始端对,没有任何重叠。
下面的代码很接近但错误,因为它输出了一个不在输入中的额外范围(我也意识到它不是很好,为什么它错了)。谁能提出更好的方法,或者我忽略的一些内置功能?
为基本问题道歉。 感谢您的帮助!
##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 """
【问题讨论】:
-
查找
Interval类。抽象可能会让你从现在正在做的工作中解放出来,并直接导致这个解决方案等等。 -
(0,5)是(1,2)的超集。你为什么不完全放弃(1,2)? -
不应该是[(0,1),(1,2),(2,4),(4,5)...]?
-
@JohnGordon 稍后需要“断点”。
-
@Accccumulation 你是对的,我更新了帖子
标签: python range aggregate union overlap