如何对JSON数组按week_year分组并计算每周total总和?
按周分组求和的可行实现方案
核心逻辑所有方案通用:以week_year为唯一分组标识,遍历所有元素累加对应total值,最后输出为目标数组格式即可,不同常用技术栈的实现代码如下:
JavaScript 实现
用数组reduce方法是最简洁的实现:
const originData = [ {"week_year": "49-2021","total": 6.5}, {"week_year": "45-2021","total": 28.5}, {"week_year": "45-2021","total": 6.5}, {"week_year": "44-2021","total": 6.5}, {"week_year": "46-2021","total": 14.5} ]; const groupedResult = Object.values(originData.reduce((acc, item) => { const weekKey = item.week_year; // 不存在该分组则初始化 if (!acc[weekKey]) acc[weekKey] = { week_year: weekKey, total: 0 }; // 累加当前值 acc[weekKey].total += item.total; return acc; }, {}));
输出的groupedResult就是分组求和后的目标数组。
Python 实现
原生Python实现(无第三方依赖)
origin_data = [ {"week_year": "49-2021","total": 6.5}, {"week_year": "45-2021","total": 28.5}, {"week_year": "45-2021","total": 6.5}, {"week_year": "44-2021","total": 6.5}, {"week_year": "46-2021","total": 14.5} ] group_dict = {} for item in origin_data: week_key = item["week_year"] group_dict[week_key] = group_dict.get(week_key, 0) + item["total"] # 转换为目标结构数组 grouped_result = [{"week_year": k, "total": v} for k, v in group_dict.items()]
用Pandas实现(适合大数据量场景)
import pandas as pd df = pd.DataFrame(origin_data) grouped_result = df.groupby("week_year", as_index=False)["total"].sum().to_dict("records")
SQL实现(数据存储在关系型数据库时)
假设你的数据存在weekly_records表中,直接用分组查询即可:
SELECT week_year, SUM(total) AS total FROM weekly_records GROUP BY week_year;
内容的提问来源于stack exchange,提问作者rjsnavarette
相关产品推荐
相关产品推荐

