我有以下时隙列表(开始日期,结束日期),按开始日期排序:
slots = [(datetime.datetime(2017, 10, 2, 6, 0), datetime.datetime(2017, 10, 2, 17, 40)),
(datetime.datetime(2017, 10, 2, 10, 35), datetime.datetime(2017, 10, 2, 16, 25)),
(datetime.datetime(2017, 10, 2, 11, 0), datetime.datetime(2017, 10, 2, 12, 0)),
(datetime.datetime(2017, 10, 2, 12, 0), datetime.datetime(2017, 10, 2, 13, 0)),
(datetime.datetime(2017, 10, 2, 15, 0), datetime.datetime(2017, 10, 2, 16, 0)),
(datetime.datetime(2017, 10, 2, 18, 0), datetime.datetime(2017, 10, 2, 19, 0))]
我想删除在此列表中另一个时隙中包含开始日期和结束日期的所有时隙。
因此,例如,在这里,最终结果应该是:
slots = [(datetime.datetime(2017, 10, 2, 6, 0), datetime.datetime(2017, 10, 2, 17, 40)),
(datetime.datetime(2017, 10, 2, 18, 0), datetime.datetime(2017, 10, 2, 19, 0))]
我尝试使用以下函数来减少它,但是它不起作用:
reduce(slots_removal, slots)
def slots_removal(a, b):
if a[1] > b[1]:
del b
这将产生:
TypeError: 'NoneType' object has no attribute '__getitem__'"
最佳答案
如果您的输入始终被排序,则可以使用生成器函数:
import datetime
def reduced(timeseries):
prev = datetime.datetime.min
for start, end in timeseries:
if end > prev:
prev = end
yield start, end
如果
(start, end)
晚于先前产生的元组,则仅产生end
元组。演示:
>>> list(reduced(slots))
[(datetime.datetime(2017, 10, 2, 6, 0), datetime.datetime(2017, 10, 2, 17, 40)), (datetime.datetime(2017, 10, 2, 18, 0), datetime.datetime(2017, 10, 2, 19, 0))]
>>> from pprint import pprint
>>> pprint(_)
[(datetime.datetime(2017, 10, 2, 6, 0),
datetime.datetime(2017, 10, 2, 17, 40)),
(datetime.datetime(2017, 10, 2, 18, 0),
datetime.datetime(2017, 10, 2, 19, 0))]
您不能使用
reduce()
;该函数从输入序列中产生单个结果。该函数的输出成为下一个调用的输入(连同下一个元素);因为您的函数没有显式返回任何内容,所以将返回None
并将其用作下一次调用的输入。关于python - 比较python中的时隙,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46012472/