So I wrote this code that returns the mean of the first three rows of a file.
import statistics
with open('data/normal_distribution.csv','r') as f:
g = f.readlines()[0:3]
for x in g:
q = str(x)
l = q.split(',')
m = list((l[:8]))
h = [float(r) for r in m]
print((statistics.mean(h)))
and I correctly get the output, which is
100.177647525
97.27899259
100.2046613525
now I want to write an additional block of code that will add the outputs of this code together, in other words, I would like to add 100.177647525, 97.27899259 and 100.2046613525 together. I tried to do this by writing this up..
import statistics
with open('data/normal_distribution.csv','r') as f:
g = f.readlines()[0:3]
for x in g:
q = str(x)
l = q.split(',')
m = list((l[:8]))
h = [float(r) for r in m]
print((statistics.mean(h)))
s = 0
for x in statistics.mean(h):
s = x
print(s)
but I'm getting an error message saying "TypeError: 'float' object is not iterable". so what changes should I make to make this work?
CodePudding user response:
You need to store the values in a variable or may be append a list with all the values like below: ####Solution 1: Store values in a list####
import statistics
with open('data/normal_distribution.csv','r') as f:
g = f.readlines()[0:3]
sum_list = []
for x in g:
q = str(x)
l = q.split(',')
m = list((l[:8]))
h = [float(r) for r in m]
print((statistics.mean(h)))
sum_list.append(statistics.mean(h))
total = sum(sum_list)
print(total)
####Solution 2: keep adding the value to a variable####
import statistics
with open('data/normal_distribution.csv','r') as f:
g = f.readlines()[0:3]
count = 0
total = 0
for x in g:
q = str(x)
l = q.split(',')
m = list((l[:8]))
h = [float(r) for r in m]
print((statistics.mean(h)))
count = statistics.mean(h)
total = total count
print(total)
I didn't run these codes yet but I think they should work.
CodePudding user response:
statistics.mean()
returns a float, not an iterator. You are actually printing this function three times, once each for your first for loop, for x in g
.
Instead of using a second for loop, just initialise a variable and add each mean to it.
import statistics
running_sum = 0
with open('data/normal_distribution.csv','r') as f:
g = f.readlines()[0:3]
for x in g:
q = str(x)
l = q.split(',')
m = list((l[:8]))
h = [float(r) for r in m]
mean = statistics.mean(h)
running_sum = mean
print(mean)
print(running_sum)