Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting while preserving order in python

Tags:

python

sorting

What is the best way to sort a list of floats by their value, whiles still keeping record of the initial order.

I.e. sorting 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.

like image 683
Theodor Avatar asked Sep 16 '10 15:09

Theodor


2 Answers

You could 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 indexing to start with 1 instead of 0, enumerate accepts the second parameter.

like image 140
SilentGhost Avatar answered Oct 07 '22 18:10

SilentGhost


  • Use enumerate to generate the sequence numbers.
  • Use sorted with a key to sort by the floats
  • Use zip to separate out the order from the values

For example:

a_order, a_sorted = zip(*sorted(enumerate(a), key=lambda item: item[1]))
like image 27
Daniel Stutzbach Avatar answered Oct 07 '22 18:10

Daniel Stutzbach