Average of entries in a list of lists

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Sep 24 05:06:03 EDT 2009


On Thu, 24 Sep 2009 01:30:10 -0700, Evora wrote:

> Hello,
> 
> I'm a bit of a newbie to python, so this may very well be a basic
> question:
> 
> I have a list of lists, with around 1000 lists looking like this:
> ['0.000744', '0.480106', 'B'].
> 
> I need the average of the first to entries of all the lists, can anybody
> help how me to do this?

This sounds rather like homework, so here are some clues rather than a 
working solution.

Let's start with a simple function to calculate the average of some 
numbers. This is so trivial you should already have this, or something 
like it:


def average(numbers):
    return sum(numbers)/float(len(numbers))


The call to float is to avoid a difficulty with division in versions of 
Python before 3.0. If you're using Python 3.0 or 3.1, you can leave it 
out. If you can guarantee that your numbers will already be floats, you 
can leave it out too. Or you can put this line at the top of your program:

from __future__ import division


Now you need another function which extracts all the numbers from your 
list-of-lists and converts them from strings to floats. 

To extract the first N items from a list L, you use:

L[:N]

For example, if you have L = ['0.1', '0.2', 1234, 'C'] and you want the 
first three items, you would say:

L[:3]

and get:

['0.1', '0.2', 1234]


Secondly, if you have a list of numbers in the form of strings:

L = ['0.1', '0.2']

and you want to get a list of actual floats, you can do this:

a, b = L
numbers = [float(a), float(b)]

but probably faster is:

numbers = map(float, L)


Thirdly, if you have a list-of-lists, and you want to combine values 
taken from each sub-list into a single summary list, you can use a 
variation on the following:


list_of_lists = [ [1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f'] ]
summary = []
for sublist in list_of_lists:
    # extract the first item
    x = sublist[0]
    # add it to the end of the summary
    summary.append(x)

# summary should now be [1, 2, 3]



Finally, if you find yourself writing something like:

x, y = sublist
L.append(x)
L.append(y)

you can save two lines by doing this:

L.extend(sublist)



Put all those pieces together, make a few minor modifications, and you 
will get a function that extracts the first two items from each sub-list, 
converts them from strings to floats, and consolidates them into a single 
summary list. Then you can pass that summary list to the average 
function, and Bob's your uncle.




-- 
Steven



More information about the Python-list mailing list