[Tutor] Averaging a list of lists with a listcomp?

John Fouhy john at fouhy.net
Thu Apr 26 06:29:44 CEST 2007


On 26/04/07, Terry Carroll <carroll at tjc.com> wrote:
> I have a list (of arbitrary length) of lists, each sublist having a fixed
> number N of items, all integers.
>
> I would like to produce a list of N items, each item of which is an
> integer which is the average of the elements in the same position of each
> of the sublists of the original list.

I don't think you're going to be able to do it with a single listcomp
based on the original list.  The reason I say this is because you need
to iterate over your _entire_ list (of arbitary length) in order to
compute _each_ element of the result list.

If you want a one-line solution, your best bet is to transform your
start list: instead of [[10, 20, 30], [50, 20, 90], [30, 20, 30]],
you'd like to have [[10,50,30], [20,20,20], [30,90,30]].  Then, it
would be easy.

Well, there's actually a simple way to do this transformation.  You
can use the zip function:

>>> zip([10, 20, 30], [50, 20, 90], [30, 20, 30])
[(10, 50, 30), (20, 20, 20), (30, 90, 30)]

And we can go a step further:

>>> orig = [[10, 20, 30], [50, 20, 90], [30, 20, 30]]
>>> zip(*orig)
[(10, 50, 30), (20, 20, 20), (30, 90, 30)]

So, here is your one-line solution:

>>> [sum(x)/len(x) for x in zip(*orig)]
[30, 20, 50]

HTH! :-)

-- 
John.


More information about the Tutor mailing list