如何在Python3中计算排行榜排名?实现指定分数排名转换
Great question! Let's walk through a few practical, efficient ways to convert your score list into the desired ranking list—where tied scores get the same rank, and subsequent ranks skip the number of tied entries.
Method 1: Using a Dictionary (No External Libraries, Efficient)
This approach is straightforward and works well for most cases, especially if you want to avoid dependencies. Here's how it works:
- Extract unique scores and sort them in descending order.
- Create a mapping from each score to its corresponding rank (starting at 1).
- Iterate over your original score list and replace each score with its rank from the mapping.
scores = [100, 100, 50, 40, 40, 20, 10] # Get unique scores sorted from highest to lowest unique_sorted_scores = sorted(set(scores), reverse=True) # Create a dictionary to map each score to its rank rank_mapping = {score: idx + 1 for idx, score in enumerate(unique_sorted_scores)} # Generate the ranking list rankings = [rank_mapping[score] for score in scores] print(rankings) # Output: [1, 1, 2, 3, 3, 4, 5]
Method 2: Using Pandas (Perfect for Data Workflows)
If you're already working with pandas (common in data analysis), the rank() method makes this trivial. We'll use method='min' to ensure tied scores get the same rank, and ascending=False to rank highest scores first.
import pandas as pd scores = [100, 100, 50, 40, 40, 20, 10] score_series = pd.Series(scores) # Calculate ranks, convert to integers, then to a list rankings = score_series.rank(method='min', ascending=False).astype(int).tolist() print(rankings) # Output: [1, 1, 2, 3, 3, 4, 5]
Method 3: Manual Index Lookup (Simple, but Less Efficient for Large Data)
For small datasets, you can directly use the index() method on a sorted list to find the first occurrence of each score, then add 1 to get the rank. Note that this has a time complexity of O(n²) since index() scans the list each time, so it's not ideal for very large lists.
scores = [100, 100, 50, 40, 40, 20, 10] # Sort the scores in descending order sorted_scores = sorted(scores, reverse=True) # For each score, find its first position in the sorted list and add 1 for rank rankings = [sorted_scores.index(score) + 1 for score in scores] print(rankings) # Output: [1, 1, 2, 3, 3, 4, 5]
All three methods will give you the exact ranking list you're looking for. Pick the one that best fits your project's context!
内容的提问来源于stack exchange,提问作者user9342203

