python - 计算日期列表中每月错误 bool 值的数量?

标签 python python-2.7

我有一个如下所示的列表,其中包含几个月内每个日期的 bool 值。我想确定每个月的 False bool 值数量,最终目标是确定每个月的每月“False”百分比。例如,如果 11 月有 15 天为假,我想显示 11 月的 50%。这如何在 Python 中完成?

list = [('2015-11-01', False), ('2015-11-02', True), ('2015-11-03', True), ('2015-11-04', True), ('2015-11-05', True)]

最佳答案

将数据存储在字典中,使用年份作为按年份分组的外键,并在每年中计算您看到 False 的次数:

from collections import defaultdict
d = defaultdict(lambda: defaultdict(float))

from calendar import monthrange, month_name
for k, v in lst:
    year, mth, _ = k.split("-")
    d[int(year)][int(mth)] += not v

for year, dct in d.items():
    for mn, v in dct.items():
        _,  days = monthrange(year, mn)
        print("Average for {}-{} is {}".format(year, month_name[mn], v / days))

获得计数后,您可以使用特定年份每月的正确天数来计算百分比。并非每年每月都有相同的天数,因此您不能使用通用日历来测试或忽略年份,日历模块会为我们处理天数。

创建一些随机数据:

from  random import choice

lst = [('2015-09-{}'.format(i), choice((True, False))) for i  in range(1,31)] + [('2015-11-{}'.format(i), choice((True, False))) for i  in range(1,31)]

输出:

Average for 2015-September is 0.533333333333
Average for 2015-November is 0.6

如果年份始终是当前年份,那么您可以将字典的创建简化为:

from collections import defaultdict
d = defaultdict(int)
for k, v in lst:
    year, mth,_= k.split("-")
    d[mth] += not v

print(d)

但请再次确保您正确比较了天数。

关于python - 计算日期列表中每月错误 bool 值的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33987797/

相关文章:

python - arcpy:程序在相交时崩溃

python-2.7 - 在 Heroku 上使用 python 运行tensorflow时出现导入错误?

python - copy() 和 deepcopy() 之间的 Python 函数

python - 计算对称表面距离 [Python]

python - 语音转文本代码卡在 "say something":

使用 cpu 查找前 5 个进程的 Python 代码

python-2.7 - 单击鼠标删除节点,networkX,python 2.7

python - 使用 Python 查找盘符 (Windows)

python - 使用 ElementTree 访问 XML 响应中的特定标记值

python - 计算给定整数中的个数