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

后端 未结 11 922
温柔的废话
温柔的废话 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:48

    I really don't get why all the existing solutions are so complex. This can be done just like this:

    [index for element, index in sorted(zip(sequence, range(len(sequence))))]
    

    You build tuples which contain the elements and a running index. Then you sort the whole thing, and tuples sort by their first element and during ties by their second element. This way one has a sorted list of these tuples and just need to pick out the indices from that afterwards. Also this removes the need to look up elements in the sequence afterwards, which likely makes it a O(N²) operation whereas this is O(N log(N)).

提交回复
热议问题