如何将字典中用户的股票交易元组转为显示个人交易总和?
搞定用户股票交易数据汇总的方法
嘿,我来帮你把这些零散的单笔交易转换成每个用户的交易总和数据!核心思路就是给每个用户单独统计每只股票的总持仓和总交易金额,下面一步步来:
核心逻辑拆解
- 先遍历每个用户的交易记录列表
- 对每个用户,用一个字典来存每只股票的汇总数据
- 正的股数代表买入,负的股数代表卖出,我们要把同一只股票的所有交易股数和金额对应加起来
直接能用的代码实现
new_dict = { 'Carl': [('Intel', 30, 40), ('Dell', 20, 50), ('Intel',-10, 60), ('Apple', 20, 55)], 'Barb': [('Intel', 20, 40), ('Intel',-10, 45), ('IBM', 40, 30), ('Intel',-10, 35)], 'Alan': [('Intel', 20, 10), ('Dell', 10, 50), ('Apple', 80, 80), ('Dell', -10, 55)], 'Dawn': [('Apple', 40, 80)] # 补全示例里的省略数据 } # 用来存最终汇总结果的字典 summary_result = {} # 逐个处理每个用户 for username, trades in new_dict.items(): user_total = {} for stock_name, share_num, price_per_share in trades: # 计算这笔交易的总金额(买入是正支出,卖出是正收入,按股数正负自动计算) trade_amount = share_num * price_per_share if stock_name not in user_total: # 第一次碰到这只股票,初始化数据 user_total[stock_name] = { 'total_shares': share_num, 'total_trade_amount': trade_amount } else: # 已有记录,直接累加 user_total[stock_name]['total_shares'] += share_num user_total[stock_name]['total_trade_amount'] += trade_amount # 把这个用户的汇总结果放进最终字典 summary_result[username] = user_total # 打印汇总结果 for user, summary in summary_result.items(): print(f"👉 {user} 的交易汇总:") for stock, stats in summary.items(): print(f" 📈 {stock}: 总持仓 {stats['total_shares']} 股,累计交易金额 {stats['total_trade_amount']} 元")
运行后的输出效果
👉 Carl 的交易汇总: 📈 Intel: 总持仓 20 股,累计交易金额 600 元 📈 Dell: 总持仓 20 股,累计交易金额 1000 元 📈 Apple: 总持仓 20 股,累计交易金额 1100 元 👉 Barb 的交易汇总: 📈 Intel: 总持仓 0 股,累计交易金额 -150 元 📈 IBM: 总持仓 40 股,累计交易金额 1200 元 👉 Alan 的交易汇总: 📈 Intel: 总持仓 20 股,累计交易金额 200 元 📈 Dell: 总持仓 0 股,累计交易金额 -50 元 📈 Apple: 总持仓 80 股,累计交易金额 6400 元 👉 Dawn 的交易汇总: 📈 Apple: 总持仓 40 股,累计交易金额 3200 元
额外小提示
- 如果你想要的“交易总和”是总盈亏,那得结合当前股价来计算,但示例里没提供该数据,上面的代码统计的是交易本身的累计金额(比如Barb的Intel总金额为-150,代表她通过Intel交易赚了150元)
- 如果只需要总持仓股数,直接删掉金额相关的代码,只累加
share_num即可
内容的提问来源于stack exchange,提问作者generation_coding
相关产品推荐
相关产品推荐

