I am trying to sort averages of scores in a class by pupil, from highest to lowest. My data is stored in text files like this:

Charlie:0
Seema:2
Amber:4
Paige:5
Amber:8
Keith:1
Charlie:8
Seema:0
Charlie:9
Seema:3
Paige:0
Paige:4
Paige:4
Charlie:1
Keith:5
Keith:3

Here is my code so far:

with open("class {0}.txt".format(Class)) as f:
    d = {}
#loop to split the data in the text file
    for line in f:
        column = line.split(":")
    #identifies the key and value with either 0 or 1
        names = column[0][Click Here](null)
        scores = int(column[1].strip())

    #appends values if a key already exists
        tries = 0
        while tries < 3:
            d.setdefault(names, []).append(scores)
            tries = tries + 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

Im quite new to Python amd i am not sure what i am doing wrong, so any pointers of help would be much appreciated, Thank you in advance!

Recommended Answers

All 5 Replies

Um, you are trying to sort a list of floas?

>>> aList = [5.5 , 4.1 , 7.6 , 2.9]
>>> sorted(aList, reverse = True)
[7.6, 5.5, 4.1, 2.9]

Or if your list is a list of lists and you want to sort each of the lists individually

>>> aList = [[2.2,1.1,3.1],[4.1,8.2,3.6]]
>>> newList = []
>>> for row in aList:
...     newList.append(sorted(row))
>>> newList
[[1.1, 2.2, 3.1], [3.6, 4.1, 8.2]]

oh, i figured out how to sort it now, I messed up my coding a bit

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

This solved it

also in line 7 of my code 'Click Here' is not supposed to be there.. (I have no idea how to edit a post)

But now i need to work out how i could only get the averages of the last three scores scores of each pupil

like this?

>>> aList
[[2.2, 1.1, 3.1], [4.1, 8.2, 3.6]]
>>> newList = []
>>> for row in aList:
...     newList.append(sum(row)/len(row))
>>> newList
[2.1333333333333333, 5.3]

Make your life easier by creating a list of (average, name) tuples. That list can be sorted as is. Something like this (stick with the default dictionary as you did before) ...

import collections as co

# assume this is a string read from a file
# showing name:score data on each line
data_str = '''\
Charlie:0
Seema:2
Amber:4
Paige:5
Amber:8
Keith:1
Charlie:8
Seema:0
Charlie:9
Seema:3
Paige:0
Paige:4
Paige:4
Charlie:1
Keith:5
Keith:3'''

# convert to a name:score_list default-dictionary
ddict = co.defaultdict(list)
for line in data_str.split():
    name, score = line.split(':')
    ddict[name].append(int(score))

print(ddict)  # test

# create a list of (average, name) tuples
averages = [(sum(scores)/len(scores), name) for name, scores in ddict.items()]

#print(averages)  # test
print(sorted(averages, reverse=True))  # test
scores = [0, 8, 9, 1]
# use slicing to get the last three scores
print(scores[-3:])  # [8, 9, 1]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.