How to take sum and average of indexed values in a list?
Question: List B is expanded at index positions where list A has adjacent matching
values using [groupby](http://docs.python.org/2/library/itertools.html)

    
    
    A = [476, 1440, 3060, 3060, 500,500]
    B = [0,4,10,15]
    

so resultant list is:

    
    
    B_update1 = [0,4,10,10,15,15]
    

which after some intermediate steps will be:

    
    
    B_update2 = [0,4,12,10,20,20]
    

Now I want to take sum and mean of duplicated values which will give me back:

    
    
    B_mean = [0,4,11,20]
    B_sum = [0,4,22,40]
    

I am not sure how to do it. Any suggestions?


Answer: 
    B_update1, B_update2, B_mean, B_sum = [0,4,10,10,15,15], [0,4,12,10,20,20], [],[]
    from itertools import groupby
    from operator import itemgetter
    for num, grp in groupby(enumerate(B_update1), itemgetter(1)):
        tmp_list = [B_update2[idx] for idx, _ in grp]
        B_mean.append(sum(tmp_list)/len(tmp_list))
        B_sum.append(sum(tmp_list))
    print B_mean, B_sum
    

**Output**

    
    
    [0, 4, 11, 20] [0, 4, 22, 40]
    

