Python sorting by score

  python

i’m new to python and i’m trying to create a leaderboard sorted by the highest score.
I have the leaderboard saved in a csv file, with name and score, then I tried to add a rank based on the sorted score.
The problem is that i don’t know why my list isn’t sorted by the score.
It would me amazing if you could help me out.


Here’s the code.

import csv

def returnScore(e):
    return e[1]
def returnRank(e):
    return e[2]

fileName = "Score.csv"

data = []

with open(fileName) as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
      data.append([row[0], row[1]])

# sort according to score
data.sort(key=returnScore, reverse=True)


# assign ranks
rank = 1
for j in range(len(data) - 1):
    if data[j][1] == data[j + 1][1]:
        if data[j][2] == data[j + 1][2]:
            data[j].append(rank)
        elif data[j][2] < data[j + 1][2]:
            data[j].append(rank)
            rank += 1
        else:
            data[j].append(rank + 1)
    else:
        data[j].append(rank)
        rank += 1

data[-1].append(rank)

# sort according to rank
data.sort(key=returnRank)

print('Leaderboard:nRankttContestanttScoret')

for item in data:
    print(item[2], item[0], item[1], sep='tt')

Source: Python Questions

LEAVE A COMMENT