Good morning, please I have a table that I'm trying to return the positions (ranks) of students scores. I have searched everywhere and I'm not getting anything better. I thought I could do it with sorting but that's not the case. This is the table:
Name Score Position
David 89 3rd
James 56 5th
Matt 72 4th
John 91 1st
Iva 56 5th
Anna 91 1st
I tried writing this code but it's not taking care of the duplicates
score = [89, 56, 72, 91, 56,91]
order = sorted(list(set(score)), reverse=True)
position = []
for n in score:
position.append(order.index(n) + 1)
print(position)
Not the pretiest code, but I think this done what you ask for:
from collections import Counter
score = [89, 56, 72, 91, 56, 91]
score_set = sorted(list(set(score)), reverse=True) # unique score
dico = dict((v, i + 1) for i, v in enumerate(score_set)) # position of unique score
count = Counter(score) # occurence of each score
total = 1 # indice to get the current position in the score
# update the dico by counting the number of duplicate.
for k, v in sorted(dico.items(), key=lambda x: x[1]): # sort the dico by the value (rank without duplicate)
count_ = count[k]
dico[k] = total
total += count_ # take into account potential duplicate
position = [dico[e] for e in score] # apply the dict to our original list
print(position) # et voilà