While we're talking about annoyances

Raymond Hettinger python at rcn.com
Sun Apr 29 15:12:17 EDT 2007


[Steven D'Aprano]
> I recently needed to write a function to generate a rank table from a
> list. That is, a list of ranks, where the rank of an item is the position
> it would be in if the list were sorted:
>
> alist = list('defabc')
> ranks = [3, 4, 5, 0, 1, 2]
. . .
> def rank(sequence):
>     table = [None] * len(sequence)
>     for j, idx in enumerate(index(sequence)):
>         table[idx] = j
>     return table

FWIW, you can do ranking faster and more succinctly with the sorted()
builtin:

def rank(seq):
    return sorted(range(len(seq)), key=seq.__getitem__)


Raymond




More information about the Python-list mailing list