python如何计算平均分_如何计算python中元组列表的平均值?

本文介绍了一种使用Python处理股票投资组合的方法,通过解析包含股票代码、价格和股份数量的列表,计算每只股票的平均购买价格及总持有数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

干得好:

the_list = [('msft', '$31', 5), ('msft','$32', 10), ('aapl', '$100', 1)]

clean_list = map (lambda x: (x[0],float (x[1][1:]), int(x[2])), the_list)

out = {}

for name, price, shares in clean_list:

if not name in out:

out[name] = [price, shares]

else:

out[name][0] += price * shares

out[name][1] += shares

# put the output in the requested format

# not forgetting to calculate avg price paid

# out contains total # shares and total price paid

nice_out = [ (name, "$%0.2f" % (out[name][0] / out[name][1]), out[name][1])

for name in out.keys()]

print nice_out

>>> [('aapl', '$100.00', 1), ('msft', '$23.40', 15)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值