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

后端 未结 11 956
温柔的废话
温柔的废话 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条回答
  •  醉话见心
    2020-12-02 20:59

    This doesn't give the exact result you specify, but perhaps it would be useful anyways. The following snippet gives the first index for each element, yielding a final rank vector of [0, 1, 2, 2, 2, 5, 6]

    def rank_index(vector):
        return [vector.index(x) for x in sorted(range(n), key=vector.__getitem__)]
    

    Your own testing would have to prove the efficiency of this.

提交回复
热议问题