我有一个[starttime in seconds, duration in seconds]
数组,像这样
[0.2, 0.4]
[0.3, 0.5]
[0.6, 0.5]
[10.6, 0.5]
我想合并重叠时间,即上述数组应转换为
[0.2, 0.9]
[10.6, 0.5]
什么是优雅的解决方案?
答案 0 :(得分:1)
假设您具有包含所有输入数据的列表,并且它们按开始时间排序
a=[[0.2,0.4],[0.3,0.5],[0.6,0.5],[10.6,0.5]] # each element is list of form [start,duration]
output =[] # output would be stored here
for x in a: # iterate through input
if output: # if we have previous output to compare
st = x[0] # current start time
dur = x[1] # current durtion time
prev_st = output[-1][0] # previous computed output start time
prev_dur = output[-1][1] # previous computed output duration
if prev_st<=st<= (prev_st+prev_dur): # check if current info can be part of previous output
updated_list=[] Update the latest output with new info
updated_list.append(prev_st) #start would remain the same as it is sorted
updated_list.append(max(prev_dur,st+dur-prev_st)) # duration can be different as per current info
output[-1] = updated_list
else:
output.append(x)
else:
output.append(x) # append first list as it is