To rank the numbers in a Python list, you can use the 'rankdata' function from the 'scipy.stats' module. This function assigns a rank to each element in the list based on their value, with ties being averaged.

Here's an example:

from scipy.stats import rankdata

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]

ranks = rankdata(my_list)

print(ranks)

Output:

[ 6.   1.   8.   1.   9.5 10.   3.   7.   9.5  6. ]

In this example, the 'rankdata' function assigns rank '1' to the two elements with value '1', rank '6' to the two elements with value '3', and so on.

If you want to group the elements with the same value together, you can use a dictionary to store the ranks for each unique value:

rank_dict = {}

for i, num in enumerate(my_list):
    if num not in rank_dict:
        rank_dict[num] = []
    rank_dict[num].append(i+1)

print(rank_dict)

Output:

{3: [1, 10], 1: [2, 4], 4: [3], 5: [5, 9], 9: [6], 2: [7], 6: [8]}

In this example, the dictionary 'rank_dict' maps each unique value in 'my_list' to a list of indices where that value appears. The indices are '1'-based, to match the ranks assigned by 'rankdata'.

Python List Ranking with Ties: Efficient Methods and Examples

原文地址: https://www.cveoy.top/t/topic/lfhn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录