Python Fun
Python Fun

Reputation: 33

Sorting averages by highest to lowest in Python from text files

I am trying to sort averages of scores in a class by pupil, from highest to lowest.

Here is my code so far:

with open("class.txt") as f:
    d = {}

    for line in f:
        column = line.split(":")
        names = column[0]
        scores = int(column[1].strip())

        count = 0
        while count < 3:
            d.setdefault(names, []).append(scores)
            count = count + 1
    for names, v in sorted(d.items()):
        average = (sum(v)/len(v))
        print(names,average)
    averages=[]
    averages.append(average)

I have worked out the averages however, I'm stuck on how I could sort these averages by highest to lowest, here is what ive tried

list = sorted(averages, key=lambda tup: tup[1], reverse=True)

However, it gives the error..

TypeError: 'float' object is not subscriptable

I also noticed that it doesn't work the averages of the last three scores only, it works out the average for all the scores of the student in the text file, however I would like it to work out only the three recent scores of each student

I'm quite new to Python and I am not sure what I am doing wrong, so any pointers of help would be much appreciated, Thank you in advance!

Upvotes: 0

Views: 4553

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125268

You have your averages code a little mixed up. Create your averages list first, then append each average you compute to that:

averages=[]
for name, v in d.items():
    average = (sum(v)/len(v))
    averages.append((name, average))

This produces a list of (name, average) tuples that you can then sort:

for name, average in sorted(averages, key=lambda a: a[1], reverse=True):
    print(name, average)

Upvotes: 2

Related Questions