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

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

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

How can I summarize stock positions to get current stocks?

 result = [('AAPL', 0), ('RY', 57)] 
+6
source share
4 answers

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)] 
+14
source

Here is a solution that is not import related:

 >>> p = [('AAPL', 50), ('AAPL', -50), ('RY', 100), ('RY', -43)] >>> d = {x:0 for x,_ in p} >>> for name,num in p: d[name] += num ... >>> Result = map(tuple, d.items()) >>> Result [('AAPL', 0), ('RY', 57)] >>> 

Please note that this is for Python 2.x. In 3.x you will need to do: Result = list(map(tuple, d.items())) .

+1
source

without explicit loops:

 >>> from itertools import groupby >>> from operator import itemgetter >>> p = [('AAPL', 50), ('AAPL', -50), ('RY', 100), ('RY', -43)] >>> map(lambda g: (g[0], sum(map(itemgetter(1), g[1]))), ... groupby(sorted(p), itemgetter(0))) [('AAPL', 0), ('RY', 57)] 
0
source

I would do this using collections.Counter :

 In [2]: from collections import Counter In [3]: c = Counter() In [4]: for k, v in p: ...: c[k] += v ...: In [5]: c Out[5]: Counter({'AAPL': 0, 'RY': 57}) 

Then you can call the most_common method of Counter objects to get a list of tuples sorted by value in descending order.

 In [5]: c.most_common() Out[5]: [('RY', 57), ('AAPL', 0)] 

If you need to sort tuples by their first elements, use sorted(c.items()) :

 In [6]: sorted(c.items()) Out[6]: [('AAPL', 0), ('RY', 57)] 
0
source

Source: https://habr.com/ru/post/951579/


All Articles