如何在动态数组的foreach循环中对同ID的数值求和
按ID汇总Amount数值的解决方案
嘿,我懂你现在的需求——把动态数组里相同ID对应的Amount数值全部加总起来对吧?这其实是个很常见的聚合需求,核心思路就是用一个哈希表(或者字典)来跟踪每个ID的累计总和,遍历数组的时候不断更新这个表就行。我给你几个主流编程语言的实现例子,你可以直接参考:
Python 实现
# 模拟你的原始数据列表 items = [ {"id": 21, "amount": 0.000}, {"id": 1, "amount": 0.000}, {"id": 2, "amount": 0.000}, {"id": 3, "amount": 0.000}, {"id": 5, "amount": 0.000}, {"id": 8, "amount": 0.000}, {"id": 1, "amount": 8.000}, {"id": 5, "amount": 1.000}, {"id": 17, "amount": 1.000}, # 这里可以继续添加剩余的项 ] # 初始化字典存储每个ID的累计总和 sum_by_id = {} for item in items: item_id = item["id"] amount = item["amount"] # 若ID已存在则累加,否则初始化为当前金额 if item_id in sum_by_id: sum_by_id[item_id] += amount else: sum_by_id[item_id] = amount # 输出最终汇总结果 for id_num, total in sum_by_id.items(): print(f"ID:{id_num} Total Amount: {total:.3f}")
JavaScript 实现
// 模拟你的原始数据数组 const items = [ {id: 21, amount: 0.000}, {id: 1, amount: 0.000}, {id: 2, amount: 0.000}, {id: 3, amount: 0.000}, {id: 5, amount: 0.000}, {id: 8, amount: 0.000}, {id: 1, amount: 8.000}, {id: 5, amount: 1.000}, {id: 17, amount: 1.000}, // 这里可以继续添加剩余的项 ]; // 用对象存储每个ID的累计总和 const sumById = {}; items.forEach(item => { const {id, amount} = item; // 短路运算简化判断:若ID不存在则默认取0,再累加当前金额 sumById[id] = (sumById[id] || 0) + amount; }); // 打印最终汇总结果 for (const id in sumById) { console.log(`ID:${id} Total Amount: ${sumById[id].toFixed(3)}`); }
Java 实现
import java.util.HashMap; import java.util.Map; public class SumAmountById { public static void main(String[] args) { // 模拟原始数据,这里用二维数组举例,你也可以用自定义实体类 Object[][] items = { {21, 0.000}, {1, 0.000}, {2, 0.000}, {3, 0.000}, {5, 0.000}, {8, 0.000}, {1, 8.000}, {5, 1.000}, {17, 1.000}, // 这里可以继续添加剩余的项 }; Map<Integer, Double> sumById = new HashMap<>(); for (Object[] item : items) { int id = (int) item[0]; double amount = (double) item[1]; // 利用getOrDefault简化判断:若ID不存在则返回0.0,再累加当前金额 sumById.put(id, sumById.getOrDefault(id, 0.0) + amount); } // 输出最终汇总结果 sumById.forEach((id, total) -> System.out.printf("ID:%d Total Amount: %.3f%n", id, total)); } }
核心思路说明
所有实现的本质都是借助哈希表(字典)的键唯一性:
- 把每个元素的ID作为哈希表的键
- 遍历数组时,若键已存在就将当前Amount加到对应的值上;若不存在就初始化键值对
- 遍历完成后,哈希表里就存储了每个ID对应的总Amount
这种方法只需要遍历数组一次,时间复杂度为O(n),效率很高,适合处理大规模数据。
内容的提问来源于stack exchange,提问作者Bigeloj
相关产品推荐
相关产品推荐

