Monday, 12 August 2013

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

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

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

No comments:

Post a Comment