Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Finding average of a nested list

Tags:

python

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

like image 957
Bruce Avatar asked Jan 28 '10 09:01

Bruce


1 Answers

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.

like image 84
Alok Singhal Avatar answered Sep 23 '22 03:09

Alok Singhal