I want to find out how to sort out averages of scores from a text file, the text file would look like this:
Matt 3
John 6
Gucci 7
Notice there is only one space inbetween the Name and Score.
From this text file i would like to work out the average of the entire files content (scores).
My current code is the following:
print("Write 'avg' to work out average of scores")
option = input ("\nEnter your Option: ")
list = []
option_class = input("\nWhich Class do you wish to preview: ")
one = "1.txt"
two = "2.txt"
if option =='avg'.lower():
if option_class == "1":
name = input("\nWhat is your name? - ")
found = False
with open(one, 'r') as f:
data = f.readlines()
for line in data:
if name in line:
print("\n",line)
list.append(int(line.split()[2]))
found = True
if found == False:
print("\nFalse")
b = sum(list)
len(list)
avg = float(sum(list))/len(list)
This is for the contents in Class 1, just for arguments sake we'll say the contents of text file 1 is the following:
Matt 3
John 6
Gucci 7
Is there an easier method in shortening the code to be more efficient or how to make it so that the code will read the text file as there is only one space between the name and score. rather than 'name - score'
答案 0 :(得分:3)
You dont have to do f.readlines()
and 'avg'.lower()
does not look like what you are intending to do, .lower()
must be used on the option
variable. Also avoid shadowing builtin functions and keywords as you did with list
.
Sample code:
print(...)
option = input(...)
option_class = input(...)
if option.lower() == 'avg' and option_class == '1': # .lower() on option.
name = input(...)
with open(one) as f: # '-r' is the default so omitting it is cleaner
# 1. iterate the file handler directly without .readlines().
# 2. use list comprehension
# 3. avoid shadowing "list" by using, say, "the_list"
the_list = [int(l.strip().split()[-1]) for l in f if l.strip() and name in l.split()]
b = sum(the_list)
length = len(the_list)
# 1. dont repeat sum() & len() calls
# 2. default to 0 avg to avoid division by 0.
avg = float(b) / length if length else 0
答案 1 :(得分:2)
As for simply opening the file and calculating the average of the numbers in its content (assuming each line is of the form [name][space][number]):
with open('1.txt', 'r') as f:
lines = f.readlines()
numbers = [float(line.split()[1]) for line in lines]
avg = float(sum(numbers)) / len(numbers)