You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对字典列表中唯一收发方对的金额求和并统计交易次数?

按收发方对统计交易总金额与次数

给定交易列表:

transactions = [
    {"Sender":"bob","Receiver":"alice","Amount":50},
    {"Sender":"bob","Receiver":"alice","Amount":60},
    {"Sender":"bob","Receiver":"alice","Amount":70},
    {"Sender":"joe","Receiver":"bob","Amount":50},
    {"Sender":"joe","Receiver":"bob","Amount":150},
    {"Sender":"alice","Receiver":"bob","Amount":100},
    {"Sender":"bob","Receiver":"kyle","Amount":260}
]

要实现按Sender/Receiver唯一对分组统计总金额和交易次数,这里提供两种实用的Python实现方法:

方法一:使用collections.defaultdict(直观易理解)

这种方法无需提前排序,直接遍历统计即可:

from collections import defaultdict

# 初始化分组统计容器,键为(Sender, Receiver)元组,值存储总金额和交易次数
stats = defaultdict(lambda: {"Total": 0, "Count": 0})

for tx in transactions:
    key = (tx["Sender"], tx["Receiver"])
    stats[key]["Total"] += tx["Amount"]
    stats[key]["Count"] += 1

# 转换为要求的字典列表格式
result = [
    {"Sender": k[0], "Receiver": k[1], "Total": v["Total"], "Count": v["Count"]}
    for k, v in stats.items()
]

print(result)

方法二:使用itertools.groupby(适合已排序的场景)

注意groupby仅对连续的相同键分组,因此需要先按Sender和Receiver排序:

from itertools import groupby

# 先按(Sender, Receiver)排序,确保相同分组连续
sorted_transactions = sorted(transactions, key=lambda x: (x["Sender"], x["Receiver"]))

result = []
for key, group in groupby(sorted_transactions, key=lambda x: (x["Sender"], x["Receiver"])):
    tx_list = list(group)
    total = sum(tx["Amount"] for tx in tx_list)
    count = len(tx_list)
    result.append({
        "Sender": key[0],
        "Receiver": key[1],
        "Total": total,
        "Count": count
    })

print(result)

两种方法的输出结果均与预期一致:

[
    {"Sender":"bob","Receiver":"alice","Total":180,"Count":3},
    {"Sender":"joe","Receiver":"bob","Total":200,"Count":2},
    {"Sender":"alice","Receiver":"bob","Total":100,"Count":1},
    {"Sender":"bob","Receiver":"kyle","Total":260,"Count":1}
]

内容的提问来源于stack exchange,提问作者piethon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 20:45:35