这将工作并打印每个30分钟间隔内的事件数:

00:00到00:30,00:30到01:00,...,23:30到24:00

import time, datetime
L = ["20231017_021000", "20231017_021100", "20231017_021200", "20231017_052800", "20231017_093100", "20231017_093900"]
d = datetime.datetime.strptime("20231017_000000", "%Y%m%d_%H%M%S")
M = [(d + datetime.timedelta(minutes=30*k)).strftime("%Y%m%d_%H%M%S") for k in range(49)]
Y = [sum([m1 < l <= m2 for l in L]) for m1, m2 in zip(M, M[1:])]
print(Y)
# [0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# => 3 events between 02:00 and 02:30
# => 1 event between 05:00 and 05:30
# => 2 events between 09:30 and 10:00

问题:它在列表L上循环48次,这可能很长.

How to do the same with a single loop pass on 100?(没有Pandas 、Numpy等,只有Python内置模块)?

推荐答案

通过计算L中每一次的间隔,然后计算该间隔中出现的次数,您可以通过对L进行单循环传递来实现这一点.

import datetime

L = ["20231017_021000", "20231017_021100", "20231017_021200", "20231017_052800", "20231017_093100", "20231017_093900"]
d = datetime.datetime.strptime("20231017_000000", "%Y%m%d_%H%M%S")

Y = [0 for _ in range(48)]

for l in L:
    # Get the time difference between the current time and the base time (in minutes)
    diff = (datetime.datetime.strptime(l, "%Y%m%d_%H%M%S") - d).seconds // 60

    # Find the interval (index in the result list)
    idx = diff // 30

    # Increment the count for that interval
    Y[idx] += 1

print(Y)

Python相关问答推荐

使用Python OpenCV的文本检测分割

为什么我的(工作)代码(生成交互式情节)在将其放入函数中时不再工作?

绘制系列时如何反转轴?

在Python中管理多个OpenGVBO和VAO实例

在Windows上启动新Python项目的正确步骤顺序

Python无法在已导入的目录中看到新模块

在内部列表上滚动窗口

Python在tuple上操作不会通过整个单词匹配

根据在同一数据框中的查找向数据框添加值

比较2 PD.数组的令人惊讶的结果

Python中的嵌套Ruby哈希

从numpy数组和参数创建收件箱

如何列举Pandigital Prime Set

Python,Fitting into a System of Equations

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

在pandas中使用group_by,但有条件

提取相关行的最快方法—pandas

在matplotlib中删除子图之间的间隙_mosaic

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''

如何删除重复的文字翻拍?