Skip to main content
 首页 » 编程设计

python之获取字典列表中的平均出现次数

2025年05月04日17lonelyxmas

给定一个字典列表(来自 MongoDB 的日志 JSON),其中字典的值之一是日期时间值,我需要知道它发生的频率。

假设:

[ 
    {"time": "2010-11-11 03:23:59"}, 
    {"time": "2010-11-12 10:16:15"}, 
    {"time": "2010-11-12 14:51:13"}, 
    ... 
] 

频率需要像这样:
一周 3 次
或者
一小时 1 次
取决于频率(如果一天不超过一次,则只返回 一天 x 次,如果不超过一周,则一周只使用 x 次,等)。

请您参考如下方法:

您可以将字符串解析为日期时间,找到最大值和最小值,减去时间增量,然后根据该时间增量指定持续时间:

import datetime as dt 
data=[ 
    {"time": "2010-11-11 03:23:59"}, 
    {"time": "2010-11-12 10:16:15"}, 
    {"time": "2010-11-12 14:51:13"}, 
    ] 
 
def freq(data): 
    dates=[dt.datetime.strptime(dct['time'],'%Y-%m-%d %H:%M:%S') for dct in data] 
    date_min=min(dates) 
    date_max=max(dates) 
    span=date_max-date_min 
    l=len(dates) 
    if span<dt.timedelta(hours=1): 
        duration='an hour' 
    elif span<dt.timedelta(hours=24): 
        duration='a day' 
    elif span<dt.timedelta(days=7): 
        duration='a week' 
    else: 
        duration='all' 
    return l,duration 
 
num,duration=freq(data) 
print('{n} times in {d}'.format(n=num,d=duration)) 

产量

3 times in a week