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.
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.
enumerate
to generate the sequence numbers.sorted
with a key
to sort by the floatszip
to separate out the order from the valuesFor example:
a_order, a_sorted = zip(*sorted(enumerate(a), key=lambda item: item[1]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With