python - Average Iterating through list -


i'm new python coming excel. want average list each new item. list:

x = [-3.2, 2.7, -8.5, -1.4] 

i've tried:

avg = sum(col)/len(col) 

and gives result of -2.6, whole column divided whole count. want return average @ each iteration. i've tried use loop:

def avg2(x):     ttl = 0     in x:         ttl +=         res = ttl / len(x)     return res 

same result, whole sum / whole column. going through whole list, not totals @ each value. reference excel formula (for numbers in column a):

=average(a$1:a4) 

when drag formula down a5, result @ iteration.

perhaps using enumerate or loop within loop?

you're not saving result anywhere during loop. returning @ end that's why getting these results:

def avg2(x):     res = []     total = 0     in x:         total +=         res.append(total / len(x))     return res 

will result in:

>>> x = [-3.2, 2.7, -8.5, -1.4] >>> avg2(x) [-0.8, -0.125, -2.25, -2.6] 

note averages total on length of entire list not number of values have been averaged far. example when averaging -0.125 it's doing -0.925 / 4 not -0.925/ 2. achieve can use enumerate , it's optional start parameter avoid division 0:

def avg2(x):     res = []     total = 0     idx, in enumerate(x, 1):         total +=         res.append(total / idx)     return res 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -