Python: Ranking Numbers in Descending Order with Duplicate Handling
To rank numbers in a descending list in Python, you can use the built-in sorted() function with the reverse=True parameter. This will sort the list in descending order.
To handle the case where the same number appears multiple times in the list and should have the same rank, you can use a dictionary to keep track of the number of times each unique value appears in the list. Then, you can iterate over the sorted list and assign ranks based on the count of each value in the dictionary.
Here's an example implementation:
def rank_list_descending(lst):
counts = {}
for num in lst:
counts[num] = counts.get(num, 0) + 1
sorted_lst = sorted(lst, reverse=True)
ranks = {}
rank = 1
for num in sorted_lst:
if num not in ranks:
count = counts[num]
ranks[num] = rank
rank += count
ranked_lst = [ranks[num] for num in lst]
return ranked_lst
This function takes a list lst as input and returns a new list with the same elements, but with each element replaced by its rank in the descending order of the list. For example:
>>> lst = [5, 2, 3, 5, 1, 4, 4]
>>> rank_list_descending(lst)
[1, 3, 2, 1, 7, 4, 4]
In this example, the list [5, 2, 3, 5, 1, 4, 4] is sorted in descending order to [5, 5, 4, 4, 3, 2, 1]. The ranks are assigned as follows:
- The first '5' gets rank 1, because it is the highest value in the list.
- The second '5' also gets rank 1, because it has the same value as the first '5'.
- The first '4' gets rank 4, because it is the fourth-highest value in the list (after the two '5's and the other '4').
- The second '4' also gets rank 4, because it has the same value as the first '4'.
- The '3' gets rank 2, because it is the second-highest value in the list (after the two '5's).
- The '2' gets rank 3, because it is the third-highest value in the list (after the two '5's and the '4').
- The '1' gets rank 7, because it is the lowest value in the list.
原文地址: https://www.cveoy.top/t/topic/lfhp 著作权归作者所有。请勿转载和采集!