I have a text file containing a string: 21.8 18.1 19 23 26 17.8
How would I convert this into a list so that I could then use it to calculate the mean?
I have a text file containing a string: 21.8 18.1 19 23 26 17.8
How would I convert this into a list so that I could then use it to calculate the mean?
To first get the contents of the file you would do:
with open("filename.txt", "r") as infile:
data = infile.read()
Now, to get a list from a string you want to use the .split()
method, so you do:
l = data.split()
Now l
is a list of strings. To convert it into a list of numbers you could use list comprehensions, and do:
l = [float(num) for num in l]
This gives you a list l
of the numbers in the file.
Hope it helped!
The solution using numpy.mean and numpy.var functions:
import numpy as np
# 21.8 18.1 19 23 26 17.8
with open('numbers.txt', 'r') as fh:
numbers = fh.read().split(' ')
np_arr = np.array(numbers).astype(np.float)
avg = np.mean(np_arr)
variance = np.var(np_arr)
print('avg: {:.2f}, variance: {:.2f}'.format(avg, variance))
The output:
avg: 20.95, variance: 8.71