I have a text file that stores data in the following format:
Mike 6 4 3
Terry 4 3 4
Paul 10 7 8
jvecsei helped me yesterday with some code to retrieve the data and identify the highest score for each person. I've modified it slightly so that it now selects the scores and prints an average for each person.
with open ("classa.txt") as f:
content = f.read().splitlines()
for line in content:
splitline = line.split(" ")
name = splitline[0]
score = splitline[1:]
total = int(splitline[-1]) + int(splitline[-2]) + int(splitline[-3])
average = int(total/3)
print("{} : {}".format (name, average))
It outputs like this, which is great:
Mike : 4
Terry : 3
Paul : 8
Question: I'd really like it to sort the three people into order of highest score so that they appear with the highest scoring person at the top and the lowest scoring at the bottom, like this:
Paul : 8
Mike : 4
Terry : 3
I have used this in the past to retrieve from a text file and sort into order alphabetically but since the average is a new variable and isn't stored in the text file with the original numbers, I don't know how to reference/implement it.
with open('classc.txt', 'r') as r:
for line in sorted(r):
print(line, end='')
Thanks very much for your help. I'm slowly becomeing more familiar with this stuff but I have a long way to go yet.