On Mon, Jul 23, 2012 at 4:02 PM, Ali Torkamani <torkam...@gmail.com> wrote: > By the way, I myself, have this solution: > >> How can we get the indices of values in the original list after sorting a >> list? >> > > (Pdb) A=[ 1, -1, 0, 7, 9, 1.3, 2.9 ] > (Pdb) sorted(zip(A, range(len(A))), key = lambda x: x[0]) > [(-1, 1), (0, 2), (1, 0), (1.3, 5), (2.9, 6), (7, 3), (9, 4)]
Here's a variation: from operator import itemgetter def sortix(seq): L, B = zip(*sorted(enumerate(seq), key=itemgetter(1))) return B, L Your original result is shaped Nx2. zip(*seq) is a quick way to transpose that to 2xN. The * operator turns each item into an argument of zip. Example: >>> A = [1, -1, 0, 7, 9, 1.3, 2.9] >>> B, L = sortix(A) >>> B (-1, 0, 1, 1.3, 2.9, 7, 9) >>> L (1, 2, 0, 5, 6, 3, 4) If you need lists, you can use map: >>> B, L = map(list, sortix(A)) >>> B [-1, 0, 1, 1.3, 2.9, 7, 9] >>> L [1, 2, 0, 5, 6, 3, 4] _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor