Sort while maintaining order in python

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.

+5
source share
4 answers

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.

+14
source
  • Use enumerateto generate sequence numbers.
  • Use sortedwith keyto sort by floats.
  • Use zipto separate order from values.

For instance:

a_order, a_sorted = zip(*sorted(enumerate(a), key=lambda item: item[1]))
+5
source

numpy:

import numpy
a=[2.3, 1.23, 3.4, 0.4]
a_sorted = numpy.sorted(a)
a_order = numpy.argsort(a)
+3
from itertools import izip
a_order, a_sorted = [list(b) for b in izip(*sorted(enumerate(a, 1), key=lambda n: n[1]))]
0

All Articles