0

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!

3
  • 1
    column[0][Click Here](null) ??? Mar 1, 2015 at 13:15
  • 1
    Is it permitted to get other people to write your GCSE exam code? Mar 1, 2015 at 13:22
  • @thefourtheye oh right, sorry, fixed it now.. no idea how that got there
    – Python Fun
    Mar 1, 2015 at 13:38

1 Answer 1

2

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)
4
  • do you perhaps have know how i could go abouts making it only work out the averages of the last three scores of each student instead of the average of all the scores of that student in the file?
    – Python Fun
    Mar 1, 2015 at 13:45
  • Take v[-3:] to get the last 3 from the list, but remove you while loop when reading the file; you are adding 3 copies of each score read.
    – Martijn Pieters
    Mar 1, 2015 at 13:48
  • @PythonFun: any reason you un-accepted my answer? Anything missing still?
    – Martijn Pieters
    Mar 4, 2015 at 22:06
  • Ooh, no nothing's missing, didn't realise i unaccepted it, I've accepted it again, Thanks for your help :)
    – Python Fun
    Mar 7, 2015 at 12:38

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.