How do I sum tuples in a list where the first value is the same?

前端 未结 4 1353
孤街浪徒
孤街浪徒 2020-11-30 12:58

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\',          


        
4条回答
  •  有刺的猬
    2020-11-30 13:18

    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)]
    

提交回复
热议问题