Average of entries in a list of lists

Xavier Ho contact at xavierho.com
Thu Sep 24 13:18:01 CEST 2009

On Thu, Sep 24, 2009 at 8:54 PM, Evora <lasse_lorentzen at hotmail.com> 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?

Say if we have:

data = [['1', '2', 'B'],
        ['2', '3', 'B'],
        ['3', '4', 'B']]

The easier way is to iterate through the big list, and get out the first
item and add them. Once you've added them all, divide by the number of lists
in the big list.

total = 0
for list in data:
    total += int(list[0])


Or there is some ... not so obvious way, but same idea:

print(sum(int(numbers[0]) for numbers in data) / len(data))


(I'm using Python 3.1 by the way. You might have to change the print

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090924/f5521368/attachment.html>

More information about the Python-list mailing list