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 中最接近的前后两个时间戳了。

相关推荐
LawrenceLan5 小时前
Flutter 零基础入门(十一):空安全(Null Safety)基础
开发语言·flutter·dart
知乎的哥廷根数学学派5 小时前
面向可信机械故障诊断的自适应置信度惩罚深度校准算法(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习·矩阵
且去填词5 小时前
DeepSeek :基于 Schema 推理与自愈机制的智能 ETL
数据仓库·人工智能·python·语言模型·etl·schema·deepseek
txinyu的博客5 小时前
解析业务层的key冲突问题
开发语言·c++·分布式
码不停蹄Zzz6 小时前
C语言第1章
c语言·开发语言
人工干智能6 小时前
OpenAI Assistants API 中 client.beta.threads.messages.create方法,兼谈一星*和两星**解包
python·llm
databook6 小时前
当条形图遇上极坐标:径向与圆形条形图的视觉革命
python·数据分析·数据可视化
行者966 小时前
Flutter跨平台开发在OpenHarmony上的评分组件实现与优化
开发语言·flutter·harmonyos·鸿蒙
阿部多瑞 ABU6 小时前
`chenmo` —— 可编程元叙事引擎 V2.3+
linux·人工智能·python·ai写作
acanab6 小时前
VScode python插件
ide·vscode·python