Reputation: 400
I have a list,
[100,100,50,40,40,20,10]
The list above is the leaderboard scores of different people. I want to convert or find their ranks and store it in a list like this:
[1,1,2,3,3,4,5]
Is there are possible way of doing something like this in Python3?
Upvotes: 3
Views: 578
Reputation: 1392
Use pandas.series
import pandas as pd
series = pd.Series(scores)
result = series.rank(method="dense", ascending=0).astype(int).values.tolist()
output:
[1, 1, 2, 3, 3, 4, 5]
Upvotes: 0
Reputation: 10369
How about this:
scores = [100,100,50,40,40,20,10]
all_scores = sorted(set(scores), reverse=True)
ranks = [all_scores.index(x) + 1 for x in scores]
print(ranks)
This prints:
[1, 1, 2, 3, 3, 4, 5]
The way this works is we take the unique elements from the list of scores (set(scores)
) and sort them in descending order. Then, we find the position of each element in scores
within that list, and add 1 to get the 1-based ranks rather than 0-based.
Upvotes: 4
Reputation: 1705
If there are two winners (e.g. rank:1), the follower should be ranked 3rd. Regarding this approach, this should do the work:
>>> grades = [100, 100, 50, 40, 40, 20, 10]
>>> ranks = [grades.index(x)+1 for x in sorted(grades, reverse=True)]
>>> ranks
[1, 1, 3, 4, 4, 6, 7]
Upvotes: 1