如何对第一个值相同的列表中的元组求和? [英] How do I sum tuples in a list where the first value is the same?

查看:46
本文介绍了如何对第一个值相同的列表中的元组求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个股票和头寸列表作为元组.买入为正,卖出为负.示例:

p = [('AAPL', 50), ('AAPL', -50), ('RY', 100), ('RY', -43)]

我如何总结股票的头寸,以获得当前持有量?

result = [('AAPL', 0), ('RY', 57)]

解决方案

这个怎么样?您可以阅读collections.defaultdict.

<预><代码>>>>从集合导入 defaultdict>>>testDict = defaultdict(int)>>>p = [('AAPL', 50), ('AAPL', -50), ('RY', 100), ('RY', -43)]>>>对于密钥,p 中的 val:testDict[key] += val>>>testDict.items()[('AAPL', 0), ('RY', 57)]

I have a list of stocks and positions as tuples. Positive for buy, negative for sell. Example:

p = [('AAPL', 50), ('AAPL', -50), ('RY', 100), ('RY', -43)]

How can I sum the positions of stocks, to get the current holdings?

result = [('AAPL', 0), ('RY', 57)]

解决方案

How about this? You can read about collections.defaultdict.

>>> from collections import defaultdict
>>> testDict = defaultdict(int)
>>> p = [('AAPL', 50), ('AAPL', -50), ('RY', 100), ('RY', -43)]
>>> for key, val in p:
        testDict[key] += val


>>> testDict.items()
[('AAPL', 0), ('RY', 57)]

这篇关于如何对第一个值相同的列表中的元组求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆