![](/img/trans.png)
[英]Is there a quick way for checking whether a date lies within n days(say 7) from a list of dates
[英]Quick way of matching date range to indices in Python list of dates
我需要选择最早日期的索引,该索引不超过date1
之前的interval
天(索引为i1
)。 我有一个排序的列表dates
,这是我要执行的操作的摘要:
for i1 in mylist:
date1 = dates[i1]
i0 = sum(1 for d in dates if date1 - d > timedelta(days = interval))
# do some other stuff with this
我找到i0
的那一行似乎是该循环的瓶颈,因为如果我将其更改为i0 = max(0, i1 - 30)
(它只是忽略丢失的日期),它的运行速度将提高大约100倍。
有没有办法加快速度? 我觉得应该有一种利用列表已排序的事实的方式,并避免进行所有比较。
PS:我的第一次尝试是:
i0 = len([d for d in dates if date1 - d > timedelta(days = interval)])
这甚至更慢。
我需要选择最早日期的索引,该索引不超过date1之前的
interval
天(索引为i1
)。 我有一个列表dates
排序
使用二进制搜索( O(log n)
时间复杂度):
import bisect
i = bisect.bisect_left(dates, dates[i1]-timedelta(days=interval))
解释bisect
的文档 :返回值i
使得切片dates[:i]
中的所有日期都大于 date[i1]
之前的( >
)个interval
天,而切片dates[i:]
中的所有日期都小于大于或等于 dates[i1]
之前的interval
天( <=
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.