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

Andreas Kostyrka andreas at kostyrka.org
Thu Apr 26 09:14:15 CEST 2007


* Terry Carroll <carroll at tjc.com> [070426 07:14]:
> 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 realize the wording above is all hash, so here's the example:
> 
> Say the original list is: [[10, 20, 30], [50, 20, 90], [30, 20, 30]]
> 
> I want the new list to be: [30, 20, 50]

Something like this?
>>> src = [[10, 20, 30], [50, 20, 90], [30, 20, 30]]
>>> [sum(x)/len(x) for x in zip(*src)]
[30, 20, 50]

Andreas


More information about the Tutor mailing list