python_时间戳对齐

需求

python 有2个保存时间戳的list, listA 和 listB, 对于listA中的每一个时间戳元素cur_ts, 查找listB中 与cur_ts最接近的前后两个时间戳元素

代码

python 复制代码
import bisect

# 示例数据
listA = [1, 5, 10, 15]
listB = [2, 6, 8, 12, 14, 18]

def find_closest_timestamps(listA, listB):
    results = []
    for cur_ts in listA:
        pos = bisect.bisect_left(listB, cur_ts)
        if pos == 0:
            closest_before = None
            closest_after = listB[0]
        elif pos == len(listB):
            closest_before = listB[-1]
            closest_after = None
        else:
            closest_before = listB[pos - 1]
            closest_after = listB[pos]
        results.append((cur_ts, closest_before, closest_after))
    return results

# 执行函数并打印结果
results = find_closest_timestamps(listA, listB)
for cur_ts, before, after in results:
    print(f"当前时间戳: {cur_ts}, 最接近的前一个时间戳: {before}, 最接近的后一个时间戳: {after}")

以上代码的工作原理如下:

  1. 使用 bisect_leftlistB 中找到插入 cur_ts 的位置 pos
  2. 根据 pos 的值来确定 cur_tslistB 中最接近的前后两个时间戳:
    • 如果 pos 为 0,说明 cur_ts 小于 listB 中的所有元素,此时没有比 cur_ts 小的元素。
    • 如果 pos 等于 listB 的长度,说明 cur_ts 大于 listB 中的所有元素,此时没有比 cur_ts 大的元素。
    • 否则,listB[pos - 1] 是最接近 cur_ts 且小于 cur_ts 的元素,listB[pos] 是最接近 cur_ts 且大于等于 cur_ts 的元素。

运行这段代码,输出结果为:

当前时间戳: 1, 最接近的前一个时间戳: None, 最接近的后一个时间戳: 2

当前时间戳: 5, 最接近的前一个时间戳: 2, 最接近的后一个时间戳: 6

当前时间戳: 10, 最接近的前一个时间戳: 8, 最接近的后一个时间戳: 12

当前时间戳: 15, 最接近的前一个时间戳: 14, 最接近的后一个时间戳: 18

这样你就可以找到 listA 中每个时间戳在 listB 中最接近的前后两个时间戳了。

相关推荐
会飞的拖把17 分钟前
Python 多任务编程:并发、进程、线程与线程安全详解
开发语言·python
君顾125 分钟前
折扣卡 CPS 小程序定制:从业务流程到系统架构的实践指南
java·开发语言·折扣卡
2601_9563198827 分钟前
看到“2026年量化学习”时,交易想法要先拆成条件和动作
人工智能·python
大模型码小白1 小时前
Harness Engineering 驾驭工程:从使用到项目实战
大数据·数据库·人工智能·python·spring
坚定学代码1 小时前
static在c++中的使用
开发语言·c++
程序员小远1 小时前
自动化测试用例编写实例详解
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
2601_962295582 小时前
Python UI自动化测试用例脚本编写指南
python·测试用例·uiautomator2·ui自动化测试·脚本编写
云雀衔光2 小时前
Java Spring AI MCP:在 Spring 里把 AI 接上你的业务系统
java·开发语言·人工智能·后端·测试工具·spring
重生之小比特2 小时前
【Java SE】数据类型与变量
java·开发语言·python
Yeniden2 小时前
Java 后端从零到企业级:第1篇 Java 基础语法——变量、数据类型与运算符
java·开发语言·apache