Finding numbers in file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson

Finding numbers in file

I have a file which contains some numbers how could I take this numbers and get the average?

12th Nov 2019, 9:51 PM
محمد اسماعيل
محمد اسماعيل - avatar
3 Answers
+ 3
First of all, you have to define how the data is stored. Are the numbers separated by ',' or by spaces... That's the most important : knowing how your numbers are stored in the file. I assume all your numbers are written on one line and separated by ','. - open the file - read the fisrt line as a string - split this string at each ',' ; it returns a list containing all the numbers as strings - convert all elements of that list into int - print the sum of the list divided by the length of the list
12th Nov 2019, 10:03 PM
Théophile - avatar
+ 1
ahhh..... you'll need to use regular expression --"findall" .... sample data would be useful. What have you been able to do so far? I've had a go and managed to get it done in three lines of code (four if you include the import re statement) it's easier than you think. correction;- Two lines of code if you import statistics module too.
12th Nov 2019, 10:13 PM
rodwynnejones - avatar
They are separated by spaces The text has lines contains letters and numbers
12th Nov 2019, 10:08 PM
محمد اسماعيل
محمد اسماعيل - avatar