Efficient method to calculate the rank vector of a list in Python

后端 未结 11 949
温柔的废话
温柔的废话 2020-12-02 20:06

I\'m looking for an efficient way to calculate the rank vector of a list in Python, similar to R\'s rank function. In a simple list with no ties between the ele

11条回答
  •  旧时难觅i
    2020-12-02 20:57

    This is one of the functions that I wrote to calculate rank.

    def calculate_rank(vector):
      a={}
      rank=1
      for num in sorted(vector):
        if num not in a:
          a[num]=rank
          rank=rank+1
      return[a[i] for i in vector]
    

    input:

    calculate_rank([1,3,4,8,7,5,4,6])
    

    output:

    [1, 2, 3, 7, 6, 4, 3, 5]
    

提交回复
热议问题