UnicornsOnLSD
UnicornsOnLSD

Reputation: 773

Sorting a list is giving out the wrong answer

I'm doing this to sort a list with high scores:

with open("scores.csv", "r") as x:
    reader = csv.DictReader(x)
    scores = []  # Makes an empty listto store the scores
    for row in reader:
        scores.append([row["Name"], row["Score"]])
    # Sorts the list by score
    scores.sort(reverse=True, key=lambda x: x[1])

But this is the output:

[['AnotherUser', '3'], ['James', '15'], ['James', '13'], ['User2', '12'], ['James', '0']]

Obviously, the result should be this:

[['James', '15'], ['James', '13'], ['User2', '12'], ['AnotherUser', '3'], ['James', '0']]

What am I doing wrong? Thanks in advance :)

Upvotes: 0

Views: 103

Answers (1)

U13-Forward
U13-Forward

Reputation: 71570

Last line should be:

scores.sort(reverse=True, key=lambda x: int(x[1]))

Instead of:

scores.sort(reverse=True, key=lambda x: x[1])

Because string comparison is very off, you know :-)

So compare the integers.

Upvotes: 5

Related Questions