以下是按照时间戳匹配没有id/key的查询性能调用的解决方法的代码示例:
import bisect
# 示例数据,假设为一个按时间排序的列表
data = [(1587895200, 'data1'), (1587896000, 'data2'), (1587896800, 'data3')]
# 时间戳查询函数
def search_by_timestamp(timestamp):
# 获取时间戳列表
timestamps = [item[0] for item in data]
# 使用二分查找找到最接近的时间戳
index = bisect.bisect_left(timestamps, timestamp)
# 如果找到的时间戳正好等于目标时间戳,则返回对应的数据
if index < len(data) and timestamps[index] == timestamp:
return data[index][1]
# 如果找到的时间戳较大,则返回前一个时间戳对应的数据
elif index > 0:
return data[index-1][1]
# 如果找到的时间戳较小,则返回后一个时间戳对应的数据
elif index < len(data):
return data[index][1]
# 如果列表为空或者目标时间戳在列表范围之外,则返回None
else:
return None
# 示例调用
timestamp = 1587896300
result = search_by_timestamp(timestamp)
if result is not None:
print(f"找到了对应的数据:{result}")
else:
print("没有找到对应的数据")
这个示例代码中使用了二分查找(bisect)来快速定位目标时间戳在已排序时间戳列表中的位置。然后根据查找到的位置,返回对应的数据。如果目标时间戳正好在列表中,则直接返回对应的数据;如果目标时间戳在列表范围之外,则返回None。
上一篇:按照时间戳排序,相同值。