python - 使用日期时间键的字典搜索

标签 python dictionary indexing python-2.7

我有时间序列数据,我目前存储在字典中,其中字典“键”是 datetime.datetime 对象。类似的东西:

data[datetime.datetime(2012,5,14,15,28,2)]={'error':error,'flags':flags,'value':value}

我的问题是:找到指定时间最近两次(之前和之后)的最佳方法是什么?我需要这个函数尽可能快,因为它被称为(~10,000) 在两个最近点之间线性插值的循环内。


我目前有一种工作方法需要很长时间,因为它会搜索所有键 (~50,000):

def findTime(time):
    keys=data.keys()
    bdt=10000000000000000000
    adt=10000000000000000000
    minKey=False
    maxKey=False
    for key in keys:
        dt=(time-key).total_seconds()
        if abs(dt)<bdt and dt>0:
            bdt=abs(dt)
            minKey=key
        elif abs(dt)<adt and dt<0:
            adt=abs(dt)
            maxKey=key
    return minKey,maxKey

我尝试使用二分法:

def findTime(time):
    keys=data.keys()
    l,r = bisect.bisect_left(time,keys), bisect.bisect_right(time,keys)
    return l,r

不幸的是,这会产生一个错误:

TypeError: 'datetime.datetime' object does not support indexing

如有任何帮助,我们将不胜感激。

最佳答案

bisect 函数的第一个参数是一个排序数组(或列表,或者实际上,任何可以索引的东西)。 keys 是一个未排序的数组,您将其作为第二个参数传递。

这应该有效:

def findTime(time):
    keys = sorted(data.keys())
    return bisect.bisect_left(keys, time), bisect.bisect_right(keys, time)

尽管您应该保留已排序的副本以用于未更改数据的重复搜索,而不是每次都重新排序。

关于python - 使用日期时间键的字典搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10590126/

相关文章:

python - 使用 Dictionary get 方法返回空列表默认​​返回 None

python - 安装 python 轮文件, '*.whl"结果为 "... is not a supported wheel on this platform"

android - 庞大MySQL数据库的高效搜索

jquery - 循环遍历 div 内的某些元素

java - 使用 SWIG 在 C 上创建面向对象的 API

java - 使用 Python 模拟输入到 Java 程序中

python - 更改键名称并添加相同键的值

arrays - 从值字典中获取数组

class - Haxe 的类(class)类型是什么?

c# - 在 C# 中查找字符串中的所有模式索引