0

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?

SyrPhys
  • 11
  • 1
  • 2
  • Possible duplicate of [How to read a file line by line into a list with Python](http://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list-with-python) – ollaw Jan 29 '17 at 22:14
  • 4
    In general when asking on SO you should show that you've tried something already. Please keep that in mind in the future. – BluCode Jan 29 '17 at 22:20

3 Answers3

0

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!

BluCode
  • 1,097
  • 7
  • 16
0

How about this?

 l = [float(v) for v in open(filename).readline().split()]
Shiping
  • 1,203
  • 2
  • 11
  • 21
0

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
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105