0

Let's say you have a list as follows:

[1,1,1,2,3,1,1,5,6,6,10]

What I would like to do, using the standard Python libraries (i.e., not numpy), is sum together any immediate duplicates. Summing the two groups of 1s and the group of 6s, the result should be (emphasis added to where summing occurs):

[**3**,2,3,**2**,5,**12**,10]

How can this be accomplished?

rhozzy
  • 332
  • 1
  • 9
  • 1
    This should be easy enough, with either explicitly looping through the list and checking for duplicates, or using [groupby](https://docs.python.org/3/library/itertools.html#itertools.groupby) from itertools. If you share your attempts I'm sure you will get help, but SO isn't for "write some code for me please" type questions [LOL, within 30 seconds of posting my comment, 3 answers appeared - 2 using groupby, 1 using a loop...] – Robin Zigmond Apr 19 '19 at 21:30

2 Answers2

3

You can use itertools.groupby and sum the outputting groups:

from itertools import groupby
l = [1,1,1,2,3,1,1,5,6,6,10]
print([sum(g) for _, g in groupby(l)])

This outputs:

[3, 2, 3, 2, 5, 12, 10]
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

Loop over the data, add to temp list if same, add sum of templist if not - do until done.

data = [1,1,1,2,3,1,1,5,6,6,10]

result = []
temp = [data[0]]
for d in data[1:]:        
    if temp[-1] == d:      # same as temp currently collects?
        temp.append(d)
    else:
        result.append(sum(temp))
        temp = [d]         # collect the new ones

result.append(sum(temp))        
print(result)  # [3, 2, 3, 2, 5, 12, 10]

Using itertools.groupby is shorter but needs an import.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69