bidby
bidby

Reputation: 738

Getting mean values out of a for loop

Fairly new to python and I have a for loop that resembles this (I won't include the contents since they seem irrelevant):

for i, (A, B) in enumerate(X):
    ...
    arbitrary calculations
    ...
    print s1
    print s2

This cycles through ten times(although it does vary occasionally), giving me 10 values for s1 and 10 for s2. Is there an efficient way of finding the means of these values?

Upvotes: 1

Views: 189

Answers (4)

Adam Smith
Adam Smith

Reputation: 54183

Sure, you can save them to do so.

lst_s1, lst_s2 = [], []

for i, (A,B) in enumerate(X):
    ...
    lst_s1.append(s1)
    lst_s2.append(s2)
    print s1
    print s2

avg_s1 = sum(lst_s1) / len(lst_s1)
avg_s2 = sum(lst_s2) / len(lst_s2)

Upvotes: 1

Saleem
Saleem

Reputation: 8978

Try following snippet to calculate mean of array. Bottom line is that it will not cause an overflow.

X = [9, 9, 9, 9, 9, 9, 9, 9]

factor = 1000000
xlen = len(X)

mean = (sum([float(x) / factor for x in X]) * factor) / xlen

print(mean)

Upvotes: 0

Farhan.K
Farhan.K

Reputation: 3485

You would need to either append each number to a list, or add them up on the fly before finding the mean.

Using a list:

s1_list = []
s2_list = []

for i, (A, B) in enumerate(X):
    ...
    arbitrary calculations
    ...
    s1_list.append(s1)
    s2_list.append(s2)

s1_mean = sum(s1_list)/float(len(s1_list))
s2_mean = sum(s2_list)/float(len(s2_list))

Adding them up on the fly:

s1_total = 0
s2_total = 0

for i, (A, B) in enumerate(X):
    ...
    arbitrary calculations
    ...
    s1_total += s1
    s2_total += s2

s1_mean = s1_total/float(len(X))
s2_mean = s2_total/float(len(X))

Use float otherwise the mean will be rounded down if it is a decimal number.

Upvotes: 2

JulienD
JulienD

Reputation: 7293

I would not allocate lists like in the other answer, just sum inside the loop and divide afterwards by the total number of elements:

sum1 = 0
sum2 = 0
for i, (A, B) in enumerate(X):
    ...
    arbitrary calculations
    ...
    sum1 += s1
    sum2 += s2

n = i+1
print(sum1/n)
print(sum2/n)

Allocation is costly if the lists grow too much bigger.

Upvotes: 1

Related Questions