Python无库实现字典列表的Group、Sum、Count、Sort数据处理
不使用第三方库实现字典列表的分组统计与排序
实现思路
我们可以通过一个临时字典完成分组统计,再将统计结果转换为目标列表并排序:
- 分组统计:遍历原始字典列表,以
name为键,累计计算每组的quantity总和、total(quantity*price_of_one的总和)以及出现次数。 - 格式转换:将临时字典中的统计结果转换为需求的字典结构。
- 排序:按照
quantity的总和进行降序排序。
完整代码实现
# 原始数据 list_data = [ {"name": "milk", "quantity": 1, "price_of_one": 2000}, {"name": "egg", "quantity": 12, "price_of_one": 500}, {"name": "egg", "quantity": 6, "price_of_one": 500}, {"name": "milk", "quantity": 2, "price_of_one": 2000}, {"name": "meat", "quantity": 1, "price_of_one": 10000} ] # 1. 分组统计临时字典 grouped = {} for item in list_data: name = item["name"] qty = item["quantity"] total = qty * item["price_of_one"] if name not in grouped: # 首次出现,初始化统计值 grouped[name] = { "quantity": qty, "total": total, "number_occurrences": 1 } else: # 累计更新统计值 grouped[name]["quantity"] += qty grouped[name]["total"] += total grouped[name]["number_occurrences"] += 1 # 2. 转换为目标列表格式 result = [] for name, stats in grouped.items(): result.append({ "name": name, "quantity": stats["quantity"], "total": stats["total"], "number_occurrences": stats["number_occurrences"] }) # 3. 按quantity总和降序排序 result.sort(key=lambda x: x["quantity"], reverse=True) # 输出结果 print(result)
运行结果
执行上述代码后,输出结果与需求完全一致:
[ {"name": "egg", "quantity": 18, "total": 9000, "number_occurrences": 2}, {"name": "milk", "quantity": 3, "total": 6000, "number_occurrences": 2}, {"name": "meat", "quantity": 1, "total": 10000, "number_occurrences": 1} ]
内容的提问来源于stack exchange,提问作者Alain Skyter
相关产品推荐
相关产品推荐

