list permutation order indices

Given a list, find the indices used to get the elements from the list in sorted order


Sometimes you need to know how a list would be sorted but not actually sort it. In the original context on comp.lang.python there was a histogram function which returned a list where the length of the list was the number of colors in the color table and the elements the repeat count of the corresponding color. To list the color values in order you need to find the position of the largest item in the histogram and get the color with the same index, then the second largest, etc.

The standard solution for this is the "DSU" (for Decorate-Sort-Undecorate), also called the Schwartzian transform from the Perl community. The 'key' parameter was added to sort in Python 2.4 to make it easier to do DSU. The key insight by Peter Otten is that the list to decorate isn't the input list, it's the indices list, and the input list's __getitem__ can be used to get the key for that index.

We benchmarked several other alternatives (see the thread "list conversion question") and this was the fastest and simplest.

# Based on a post by Peter Otten on comp.lang.python 2004/09/04.
# This uses the 'key' option to sort and the 'sorted' function, both
# new in Python 2.4.

def permutation_indices(data):
     return sorted(range(len(data)), key = data.__getitem__)

if __name__ == "__main__":
     import sys
     chars = "Sing a song of six-pence."
     print chars
     print   "0         1         2     "
     print   "01234567890123456789012345"
     print
                    
     indices = permutation_indices(chars)
     for i in indices:
          print "%4s %r" % (i, chars[i])

# Sing a song of six-pence.
# 0         1         2     
# 01234567890123456789012345
# 
#    4 ' '
#    6 ' '
#   11 ' '
#   14 ' '
#   18 '-'
#   24 '.'
#    0 'S'
#    5 'a'
#   22 'c'
#   20 'e'
#   23 'e'
#   13 'f'
#    3 'g'
#   10 'g'
#    1 'i'
#   16 'i'
#    2 'n'
#    9 'n'
#   21 'n'
#    8 'o'
#   12 'o'
#   19 'p'
#    7 's'
#   15 's'
#   17 'x'

code.activestate.com ↗