Thursday, July 30, 2009

Python: Sort List and return Index of original Unsorted Item

I’ve been staying up all night to revise my research paper which will going to be submitted as a final submission for IEEE Symposium on Industrial Electronics and Applications (ISIEA 09).

Most of the night was spent by working with the python code to make a comparison based on the test data and training data-set to be included as a result findings in the paper.

One problem occurs when I want to sort the array list of the result data but still want to keep the original unsorted index for future reference. The searching and asking process took place and several solutions to this problem found.
  1. build a mapping from values to the original index before sorting the list
  2. build a list of (value, pairs) pairs and sort that list instead of the original array list
  3. don’t sort at all, just sort a copy
  4. sorted(enumerate(arrayname), key=operator.itemgetter(1))
and definitely I choose the 4th solutions, which is not much working need to be done.

Below are the steps and output,
>> myarray = [2, 3, 1, 4, 5]
>> import operator
>> sorted(enumerate(myarray), key=operator.itemgetter(1))
[(2, 1), (0, 2), (1, 3), (3, 4), (4, 5)]