How to do the following operation in python in tricky way?
Question: I have a list of tuples as follows

    
    
    [(1,4),(3,5),(2,9),(6,23),(3,21),(2,66),(5,20),(1,33),(3,55),(1,8)]
    

Now I need something like this

  1. In the above list, each element is a tuple and the first item in a tuple is an index and the second item is a value.
  2. We need to multiply all the tuple values whose indices are equal and then add all the multiplication result for all indices. 
  3. If there is only once tuple with certain index, we have to make the multiplication result zero for that. That means that tuple does not contribute to the final sum.

I would be so much obliged if some one can help me. I am new in python so
finding it difficult.


Answer: Here's one way to do it. Use `itertools.groupby` to create groups
corresponding to each index, multiply and add

    
    
    from operator import itemgetter, mul
    from itertools import groupby
    z = [(1,4),(3,5),(2,9),(6,23),(3,21),(2,66),(5,20),(1,33),(3,55),(1,8)]
    z = sorted(z, key=itemgetter(0))
    z = groupby(z, key=itemgetter(0))
    z = ((key, list(value for (key, value) in groups)) for (key, groups) in z)
    z = ((key, reduce(mul, values, 1)) for (key, values) in z if len(values) > 1)
    z = sum(value for (key, value) in z)
    print z
    7425
    

