Python: Sum Immediate Duplicates in List

Question:

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?

Asked By: rhozzy

||

Answers:

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]
Answered By: blhsing

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.

Answered By: Patrick Artner
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.