我尝试在python中的两个二维列表(包含时间范围)中找到重叠。我发现了一些相关的问题,但是大多数问题只涉及一维列表。如果您有一个已解决的问题,则非常感谢您的链接。
所以我得到了两个列表,(开始,结束,持续时间都是时间的整数值,以毫秒为单位)
TargetSegments =[[Start,End,Duration],[Start,End,Duration],...]
BackchannelSegments =[[Start,End,Duration],[Start,End,Duration],...]
现在我要获取一个新列表,其中包含[startOverlap,endOverlap,durationOverlap]形式的元素
我的第一种方法是使用for循环,但是它有点复杂,我不确定这是否是最有效的方法
这就是我当前的功能。首先,将列表中包含的字符串转换为整数值(对于ms; ps:str2ms是我自己编写的函数,它只需要一个类似时间的字符串,即“ 1:32:23”并计算相应的时间以毫秒为单位)
def removeBackchannels(self,SegmentsTarget,SegmentsBackchannel):
#Converts the string for the segments in ms
c_SegmentsTarget = []
c_SegmentsBackchannel = []
for start,end,duration in SegmentsTarget:
c_SegmentsTarget.append([str2ms(start),str2ms(end),str2ms(duration)])
for start,end,duration in SegmentsBackchannel:
c_SegmentsBackchannel.append([str2ms(start),str2ms(end),str2ms(duration)])
for segmentTar in c_SegmentsTarget:
for segmentBC in c_SegmentsBackchannel:
if segmentTar[0] < segmentBC[0] < segmentTar[1]: #if BC Start is before end of the Segmnet
startOverlap = segmentBC[0]
if segmentBC[1] > segmentTar[1]:
endOverlap = segmentTar[1]
else:
endOverlap = segmentBC[1]
durationOverlap = endOverlap - startOverlap
overlaps.append([startOverlap,endOverlap,durationOverlap])
print "Found Overlap at: %s - %s (%s)" % (startOverlap,endOverlap,durationOverlap)
elif segmentTar[1] > segmentBC[1] > segmentTar[0]: #if BC End is after the start of the Segment
startOverlap = segmentTar[0]
endOverlap = segmentBC[1]
durationOverlap = endOverlap - startOverlap
overlaps.append([startOverlap,endOverlap,durationOverlap])
print "Found Overlap at: %s - %s (%s)" % (startOverlap,endOverlap,durationOverlap)
if segmentBC[0] > segmentTar[1]: #If start of the back channel is behind the end of the segment of interest
break
print len(overlaps)
首先,我不确定我是否能够使用这种方法来解决所有重叠问题,或者我的if陈述是否足够?其次,如果有一种更Python化或更有效的方式来获得重叠,那就太好了。
非常感谢和问候