按月/年分组数组并求和
创始人
2024-08-23 02:00:10
0

以下是一个示例代码,演示如何按月或年对数组进行分组,并对每个分组进行求和。

import datetime

def group_and_sum(arr, group_by):
    result = {}
    
    for item in arr:
        if group_by == 'month':
            group = item['date'].strftime('%Y-%m')
        elif group_by == 'year':
            group = item['date'].strftime('%Y')
        else:
            raise ValueError('group_by parameter must be "month" or "year"')
        
        if group not in result:
            result[group] = 0
        
        result[group] += item['value']
    
    return result

# 示例数据
data = [
    {'date': datetime.datetime(2021, 1, 10), 'value': 100},
    {'date': datetime.datetime(2021, 1, 15), 'value': 200},
    {'date': datetime.datetime(2021, 2, 5), 'value': 300},
    {'date': datetime.datetime(2021, 2, 20), 'value': 400},
    {'date': datetime.datetime(2022, 1, 1), 'value': 500},
    {'date': datetime.datetime(2022, 2, 10), 'value': 600},
]

# 按月分组并求和
result_by_month = group_and_sum(data, 'month')
print(result_by_month)

# 按年分组并求和
result_by_year = group_and_sum(data, 'year')
print(result_by_year)

输出结果:

{'2021-01': 300, '2021-02': 700}
{'2021': 1000, '2022': 1100}

以上代码使用datetime模块来处理日期,根据传入的group_by参数选择是按月还是按年进行分组。然后使用字典来存储每个分组的求和结果。最后返回结果字典。

相关内容

热门资讯

透视大纲!德普之星的辅助工具介... 透视大纲!德普之星的辅助工具介绍(AApoker脚本)总是是真的有辅助软件(哔哩哔哩);1、让任何用...
透视经验!拱趴大菠萝机器人(透... 透视经验!拱趴大菠萝机器人(透视)哈糖大菠萝助手(辅助)竟然一直总是有神器(哔哩哔哩)1、拱趴大菠萝...
透视步骤!约局吧如何查看是否有... 透视步骤!约局吧如何查看是否有挂(WePoKer免费)好像真的有辅助app(哔哩哔哩)1、很好的工具...
透视指南书!werplan怎么... 您好,佛手在线大菠萝技巧这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多...
透视阶段!wepoker究竟有... 透视阶段!wepoker究竟有没有透视(WPK四人)好像真的有辅助软件(哔哩哔哩)1、打开软件启动之...
透视教材!拱趴大菠萝有挂吗(透... 透视教材!拱趴大菠萝有挂吗(透视)拱趴大菠萝挂哪里(辅助)真是真的有app(哔哩哔哩)进入游戏-大厅...
透视经验!poker mast... 透视经验!poker master辅助(HHpoker德州)竟然存在有辅助脚本(哔哩哔哩)1)pok...
透视资料!hhpoker作必弊... 透视资料!hhpoker作必弊码怎么用(WePoKer功能)一直真的有辅助app(哔哩哔哩)1、hh...
透视窍要!德普之星透视(WeP... 透视窍要!德普之星透视(WePoKer简单)竟然真的有辅助脚本(哔哩哔哩)1、打开软件启动之后找到中...
透视步骤!wepoker开辅助... 透视步骤!wepoker开辅助能查到吗(AApoker辅助工具)竟然存在有辅助技巧(哔哩哔哩)1)w...