tags:

views:

126

answers:

5

I have a list

a = [[1,2,3],[4,5,6],[7,8,9]]

Now I want to find the average of these inner list so that

a = [(1+4+7)/3,(2+5+8)/3,(3+6+9)/3]

'a' should not be a nested list in the end. Kindly provide an answer for the generic case

A: 

EDIT: See Alok's answer for correct solution.

Kimvais
Argh, apparently I cannot read. :)
Kimvais
+8  A: 
a = [sum(x)/len(x) for x in zip(*a)]
# a is now [4, 5, 6] for your example

In Python 2.x, if you don't want integer division, replace sum(x)/len(x) by 1.0*sum(x)/len(x) above.

Documentation for zip.

Alok
+1 for zip, but couldn't you save yourself the trouble of an extra function? ;)
Tor Valamo
I figured that the OP didn't know Python too well. Editing anyway :-)
Alok
+2  A: 
>>> import itertools
>>> [sum(x)/len(x) for x in itertools.izip(*a)]
[4, 5, 6]
S.Mark
+1  A: 

oops sorry: i read the question wrong. well my fix looks pretty much the same as above.

nick
except that it isn't.
SilentGhost
+1  A: 

If you have numpy installed:

>>> import numpy as np
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> arr = np.array(a)
>>> arr
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.mean(arr)
5.0
>>> np.mean(arr,axis=0)
array([ 4.,  5.,  6.])
>>> np.mean(arr,axis=1)
array([ 2.,  5.,  8.])
telliott99