ID:
将时间戳列表转换为datetime
对象:
times = [datetime.datetime.strptime(t, '%Y-%m-%d %H:%M:%S') for t in times]
使用该bisect
模块查找用户请求的开始时间。使用bisect
是比使用线性搜索更快的方法,前提是您也将用户输入转换为datetime
对象:
start = datetime.datetime(2002, 3, 31, 19, 53, 17)
startindex = bisect.bisect_left(times, start)
使用itertools
函数将两个列表合并为一个显示与您的范围匹配的条目:
end = datetime.datetime(2002, 4, 1, 07, 53, 17)
merged = itertools.izip(times, activity)
fromstart = itertools.islice(merged, startindex)
untilend = itertools.takewhile(lambda e: e[0] <= end, fromstart)
untilend
iterable 现在在元组之间和元组之间生成条目,start
而end
无需(time, activity)
为复制的列表使用任何额外的内存。这让您可以有效地处理大量数据。
演示:
>>> import itertools
>>> import datetime
>>> import bisect
>>> times = ['2002-03-31 19:30:41', '2002-03-31 19:30:41', '2002-03-31 19:43:49', '2002-03-31 19:43:50', '2002-03-31 19:50:05', '2002-03-31 19:50:06', '2002-03-31 19:50:06', '2002-03-31 19:50:44', '2002-03-31 19:50:45', '2002-03-31 19:50:45', '2002-03-31 19:51:50', '2002-03-31 19:51:50', '2002-03-31 19:51:50', '2002-03-31 19:52:25', '2002-03-31 19:52:25', '2002-03-31 19:52:25', '2002-03-31 19:53:05', '2002-03-31 19:53:06', '2002-03-31 19:53:06', '2002-03-31 19:53:06', '2002-03-31 19:53:17', '2002-03-31 19:54:14', '2002-03-31 19:54:14']
>>> activity= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w']
>>> times = [datetime.datetime.strptime(t, '%Y-%m-%d %H:%M:%S') for t in times]
>>> start = datetime.datetime(2002, 3, 31, 19, 53, 17)
>>> end = datetime.datetime(2002, 4, 1, 07, 53, 17)
>>> startindex = bisect.bisect_left(times, start)
>>> merged = itertools.izip(times, activity)
>>> fromstart = itertools.islice(merged, startindex)
>>> untilend = itertools.takewhile(lambda e: e[0] <= end, fromstart)
>>> for time, activity in untilend:
... print time, activity
...
2002-03-31 19:30:41 a
2002-03-31 19:30:41 b
2002-03-31 19:43:49 c
2002-03-31 19:43:50 d
2002-03-31 19:50:05 e
2002-03-31 19:50:06 f
2002-03-31 19:50:06 g
2002-03-31 19:50:44 h
2002-03-31 19:50:45 i
2002-03-31 19:50:45 j
2002-03-31 19:51:50 k
2002-03-31 19:51:50 l
2002-03-31 19:51:50 m
2002-03-31 19:52:25 n
2002-03-31 19:52:25 o
2002-03-31 19:52:25 p
2002-03-31 19:53:05 q
2002-03-31 19:53:06 r
2002-03-31 19:53:06 s
2002-03-31 19:53:06 t