Reputation: 773
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
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