Compute the average of the same index in the list, python
Question: I have a list as follows:

    
    
    A= [('1', 3), ('2', 7), ('3', 5), ('1', 7), ('2', 5), ('3', 1)]
    

From the list `A`, I would like to generate the output list like this:

    
    
    Average = [('1', 5), ('2', 6), ('3', 2)]
    

Any tips would be really grateful! =)


Answer: 
    from collections import defaultdict
    a = [('1', 3), ('2', 7), ('3', 5), ('1', 7), ('2', 5), ('3', 1)]
    d = defaultdict(list)
    for k, v in a:
        d[k].append(v)
    avg = [(k, sum(v) // len(v)) for k, v in d.iteritems()]
    print avg
    

prints

    
    
    [('1', 5), ('3', 3), ('2', 6)]
    

Note that this uses integer division to compute the averages. You might want
to use floating point division instead.

