How can I calculate the average of a list of tuples in python?
Question: I have a list of tuples in the format:

[(security, price paid, number of shares purchased)....]

    
    
    [('MSFT', '$39.458', '1,000'), ('AAPL', '$638.416', '200'), ('FOSL', '$52.033', '1,000'), ('OCZ', '$5.26', '34,480'), ('OCZ', '$5.1571', '5,300')]
    

I want to consolidate the data. Such that each security is only listed once.

[(Name of Security, Average Price Paid, Number of shares owned), ...]


Answer: It's not very clear what you're trying to do. Some example code would help,
along with some information of what you've tried. Even if your approach is
dead wrong, it'll give us a vague idea of what you're aiming for.

In the meantime, perhaps numpy's `numpy.mean` function is appropriate for your
problem? I would suggest transforming your list of tuples into a numpy array
and then applying the mean function on a slice of said array.

That said, it does work on any list-like data structure and you can specify
along which access you would like to perform the average.

<http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html>

**EDIT:**

From what I've gathered, your list of tuples organizes data in the following
manner:

    
    
    (name, dollar ammount, weight)
    

I'd start by using numpy to transform your list of tuples into an array. From
there, find the unique values in the first column (the names):

    
    
    import numpy as np
    a = np.array([(tag, 23.00, 5), (tag2, 25.00, 10)])
    unique_tags = np.unique(a[0,:])  # note the slicing of the array
    

Now calculate the mean for each tag

    
    
    meandic = {}
    for element in unique_tags:
       tags = np.nonzero(a[0,:] == element)  # identify which lines are tagged with element
       meandic[element] = np.mean([t(1) * t(2) for t in a[tags]])
    

Please note that this code is untested. I may have gotten small details wrong.
If you can't figure something out, just leave a comment and I'll gladly
correct my mistake. You'll have to remove '$' and convert strings to floats
where necessary.

