我已经对 datetime.time 列表进行了排序,并希望创建类似的间隔。如果我有
a = [datetime.time(0,0), datetime.time(8,0), datetime.time(13,0), datetime.time(17,0)]
那么结果应该是这样的:
c = [[datetime.time(0,0),datetime.time(8,0)], [datetime.time(8,0),datetime.time(13,0)],
[datetime.time(13,0),datetime.time(17,0)], [datetime.time(17,0),datetime.time(0,0)]]
这可以使用简单的循环来实现,但是否存在更好的解决方案?
使用循环:
>>> a=[datetime.time(0, 0), datetime.time(3, 0), datetime.time(8, 0), datetime.time(11, 0)]
>>>
>>> r = []
>>>
>>> for i in range(0,len(a)):
... if i+1 < len(a):
... r.append([a[i],a[i+1]])
... else:
... r.append([a[i],a[0]])
...
>>> r
[[datetime.time(0, 0), datetime.time(3, 0)], [datetime.time(3, 0), datetime.time(8, 0)], [datetime.time(8, 0), datetime.time(11, 0)], [datetime.time(11, 0), datetime.time(0, 0)]]
>>>
如果我想要结果是什么可以改变
[[datetime.time(0, 0), datetime.time(2, 59, 59)], [datetime.time(3, 0), datetime.time(7, 59, 59)], [datetime.time(8, 0), datetime.time(10, 59, 59)], [datetime.time(11, 0), datetime.time(23, 59, 59)]]