计算时间戳的计数

Calculating count of timestamp

我有兴趣计算时间戳在 30 天内发生五次的事件。

我创建了一个函数,我觉得这离 pythonic 还很远。

有什么方法可以使用集合或迭代器或 lambda。

这是我写的代码:

def has_five_or_more_in_ANY_30_days(timestamps):

    for i in range(timestamps):
        from_value = timestamps[i]
        to_value = from_value + (30 * 24 * 60 * 60)

        counts = 0
        for ts in timestamps:
            if ts > from_value and ts < to_value:
                counts += 1
                if counts >=5:
                    return True
                else:
                    return False

timestamps = [ 1416182478, 1416182479, 1416182480, 1416182481, 1416182481, 1416182481, 1416182481,1416182481,1416182481,1416182482,1416182483,1416182484, 1416182485, 1416182486,1416182487, 1416182488,1416182489, 1416182490 ]

print has_five_or_more_in_ANY_30_days( timestamps )

代码对你不起作用,因为你在内部循环本身中 returning False,所以你总是 return False ,因为你初始化了count 为 0 ,并且在第一次迭代中 ou 仅将 count 增加 1 ,因此 count 为 1 ,并且不大于 5,因此您 return False 。为了使您的特定代码正常工作,您需要将 return False 移动到外部循环之外,直接在函数内部,else 块不应该在那里。


鉴于您可以简化代码,使用以下方法-

  1. 首先将时间戳从低到高排序。

  2. 然后检查每个 timestamp 之间的差异,并将其添加到一个值中,对每 5 个连续项目执行此操作。最后,如果 5 个连续时间戳的相加差小于 30 * 24 * 60 * 60 ,则表示这 5 个日期在 30 天范围内,此时可以 return True。

  3. 如果没有找到这样的匹配项,return 错误。

示例代码-

def has_five_or_more_in_ANY_30_days(timestamps):
    tssorted = sorted(timestamps)
    time_to_check = 30 * 24 * 60 * 60
    for i in range(0,len(tssorted)-5):
        time_diff = 0
        for j in range(i+1,i+5):
            time_diff += tssorted[j] - tssorted[i]
        if time_diff < time_to_check:
            return True
    return False