在一个时间跟踪应用中,一天被分成五个部分。
0: 00 - 6: 00, 6: 00 - 14: 00, 14: 00 - 20: 00, 20: 00 - 23: 00, 23: 00 - (无穷大)
这五个 "仓 "需要根据其中任何一个仓的时间来填充.比如说有关的时间间隔从5:00开始到16:00结束,1号仓包含1个小时,2号仓包含8个小时,3号仓包含2个小时,4号仓包含0个小时,5号仓包含0个小时.任何时间,超过23:00就进入5号仓。
到目前为止,我想出了这样的方法。
sections = [ 0, 0, 0, 0, 0 ]
for tframe in numericdata:
if tframe[0] < 6.00: # starts before 6:00
if tframe[1] >= 6.00: # ends after 6:00
sections[0] += 6.00 - tframe[0]
else: # ends before 6:00
sections[0] += tframe[1] - tframe[0]
continue
if tframe[1] >= 14.00: # ends after 14:00
sections[1] += 14.00 - 6.00
else: # ends between 6:00 and 14:00
sections[1] += tframe[1] - 6.00
continue
if tframe[1] >= 20.00: # ends after 20:00
sections[2] += 20.00 - 14.00
else: # ends between 14:00 and 20:00
sections[2] += tframe[1] - 14.00
continue
if tframe[1] >= 23.00: # ends after 23:00
sections[3] += 23.00 - 20.00
sections[4] += tframe[1] - 23.00
else: # ends between 20:00 and 23:00
sections[3] += tframe[1] - 20.00
continue
elif tframe[0] < 14.00: # starts between 6:00 and 14:00
if tframe[1] >= 14.00: # ends after 14:00
sections[1] += 14.00 - tframe[0]
else: # ends before 14:00
sections[1] += tframe[1] - tframe[0]
continue
if tframe[1] >= 20.00: # ends after 20:00
sections[2] += 20.00 - 14.00
else: # ends between 14:00 and 20:00
sections[2] += tframe[1] - 14.00
continue
if tframe[1] >= 23.00: # ends after 23:00
sections[3] += 23.00 - 20.00
sections[4] += tframe[1] - 23.00
else: # ends between 20:00 and 23:00
sections[3] += tframe[1] - 20.00
continue
elif tframe[0] < 20.00: # starts between 14:00 and 20:00
if tframe[1] >= 20.00: # ends after 20:00
sections[2] += 20.00 - tframe[0]
else: # ends before 20:00
sections[2] += tframe[1] - tframe[0]
continue
if tframe[1] >= 23.00: # ends after 23:00
sections[3] += 23.00 - 20.00
sections[4] += tframe[1] - 23.00
else: # ends between 20:00 and 23:00
sections[3] += tframe[1] - 20.00
continue
elif tframe[0] < 23.00: # starts between 20:00 and 23:00
if tframe[1] >= 23.00: # ends after 23:00
sections[3] += 23.00 - tframe[0]
sections[4] += tframe[1] - 23.00
else: # ends before 23:00
sections[3] += tframe[1] - tframe[0]
continue
else: # starts and ends some time after 23:00
sections[4] += tframe[1] - tframe[0]
numericdata
是一个数组,包含了开始和结束时间的元组。所有的时间值都已经用分数转换为小时,所以13:15被编码为13.25,等等。numericdata
可包含 [ [ 6.75, 12.5 ], [ 13.5, 18.25 ] ]
所以两个区间,一个是6:45到12:30,另一个是13:30到18:15。结果是 sections
数组会是这样的。[ 0, 6.25, 4.25, 0, 0 ]
我觉得一定有更好的方法来做这件事 而不是像我现在这样。它完全是硬编码的,我不能想出一些构造,以减少代码的重复,也许是更灵活一点,例如定义仓的数量和它们的长度,而不是像这样硬编码。
先谢谢你了!
希望我对你的问题理解正确。的 裂开 列表中定义了小时数 splits
所以它是可配置的。
data = [[ 6.75, 12.5 ], [ 13.5, 18.25 ]]
splits = [0, 6, 14, 20, 23, float('inf')]
def intersection(a, b, c, d):
if a > d or b < c:
return 0 # no intersection
left, right = max(a, c), min(b, d)
return right - left
out = [sum(v) for v in zip(*[[intersection(*i, *s) for s in zip(splits, splits[1::])] for i in data])]
print(out)
打印:
[0, 6.25, 4.25, 0, 0]