index of items in a List in sorted order

Bengt Richter bokr at oz.net
Sun Nov 24 22:20:40 EST 2002


On 24 Nov 2002 18:41:01 -0800, nbatada1 at yahoo.com (Nizar Batada) wrote:

>I am posting a code to get index of sorted list for 
>future reference.
>if you can make this code faster, i'll appreciate your input
>nizar
>########################################################3
>#!/usr/bin/python
>
>def ind_of_sorted(L):
>        ''' return index of items in sorted order '''
>	k = len(L)
>	d = {}
>	# take care of repeated values
>	[ d.setdefault(L[i],[]).append(i) for i in range(k)]
>	auxL = d.keys()
>	auxL.sort()
>	inds = []
>	[inds.extend( d[x] ) for x in auxL]
>	return auxL,inds
>
>if __name__ == '__main__':
>	L=['r','g','a','f','r','j']
>	Lsort,Lsort_I=ind_of_sorted(L)
>	print L
>	print Lsort
>	print Lsort_I

 >>> def ind_of_sorted2(L):
 ...     items = zip(L,range(len(L)))
 ...     items.sort()
 ...     return zip(*items)
 ...
 >>> ind_of_sorted2(list('rgafrj'))
 [('a', 'f', 'g', 'j', 'r', 'r'), (2, 3, 1, 5, 0, 4)]

Of course, it doesn't eliminate the duplicates, but now there's
probably some time left to do that ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list