6

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.

4 Answers 4

17

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.

Sign up to request clarification or add additional context in comments.

7 Comments

aorder, asorted = zip(*sorted(enumerate(a), key=lambda x: x[1]) for completeness.
I'd be pretty sure, OP would need to zip his two lists back at one stage.
itemgetter would have been better than lambda
@dugres: huh? why is that? I'm no fan of lambdas, but if they have a use in python it's here.
@SilentGhost: itemgetter, also, has many use and this is a good one. key=itemgetter(1)
|
5
  • 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]))

Comments

3

If you have numpy installed:

import numpy
a=[2.3, 1.23, 3.4, 0.4]
a_sorted = numpy.sorted(a)
a_order = numpy.argsort(a)

1 Comment

This is nice for a guy more used to matlab then python =)
0
from itertools import izip
a_order, a_sorted = [list(b) for b in izip(*sorted(enumerate(a, 1), key=lambda n: n[1]))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.