What is the best way to sort the list of floats by their value, while still retaining the entry of the initial order.
those. sort a:
a=[2.3, 1.23, 3.4, 0.4]
returns something like
a_sorted = [0.4, 1.23, 2.3, 3.4] a_order = [4, 2, 1, 3]
If you catch my drift.
You can do something like this:
>>> sorted(enumerate(a), key=lambda x: x[1]) [(3, 0.4), (1, 1.23), (0, 2.3), (2, 3.4)]
If you need to index to start with 1 instead of 0, it enumeratetakes a second parameter.
enumerate
sorted
key
zip
For instance:
a_order, a_sorted = zip(*sorted(enumerate(a), key=lambda item: item[1]))
numpy:
numpy
import numpy a=[2.3, 1.23, 3.4, 0.4] a_sorted = numpy.sorted(a) a_order = numpy.argsort(a)
from itertools import izip a_order, a_sorted = [list(b) for b in izip(*sorted(enumerate(a, 1), key=lambda n: n[1]))]