Python: Ranking Scores in Descending Order with Equal Rank Handling
One way to achieve this is by using the sorted() function to sort the list in descending order, and then iterate over the sorted list to assign ranks to each score. Here's an example implementation:
scores = [85, 92, 76, 92, 88, 76, 90, 89, 82]
# sort the scores in descending order
sorted_scores = sorted(scores, reverse=True)
# initialize the rank counter and the rank dictionary
rank = 1
rank_dict = {}
# iterate over the sorted scores and assign ranks
for score in sorted_scores:
if score not in rank_dict:
rank_dict[score] = rank
rank += 1
# create a list of ranks for each original score
rank_list = [rank_dict[score] for score in scores]
print(rank_list)
# output: [3, 1, 5, 1, 2, 5, 4, 6, 8]
In this example, the sorted scores are [92, 92, 90, 89, 88, 85, 82, 76, 76]. We initialize the rank counter to 1 and the rank dictionary to an empty dictionary. Then, we iterate over the sorted scores and if a score is not already in the rank dictionary, we assign it the current rank and increment the rank counter. Finally, we create a list of ranks for each original score by looking up the score in the rank dictionary. The output is [3, 1, 5, 1, 2, 5, 4, 6, 8], which shows the rank of each score in the original list.
原文地址: https://www.cveoy.top/t/topic/lfhq 著作权归作者所有。请勿转载和采集!