How to sort the python list that contains the float values,
list1 = [1, 1.10, 1.11, 1.1, 1.2]
or
list1 = ['1', '1.10', '1.11', '1.1', '1.2']
The expected results is
list_val = ['1', **'1.1', '1.2'**, '1.10', '1.11']
but the returned result in using sort() method returns
[1, 1.1000000000000001, 1.1000000000000001, 1.1100000000000001, 1.2]
or
['1', '1.1', '1.10', '1.11', '1.2'].
But, here 1.2
should come in between 1.1
and 1.10
.
float_sort is a fast templated in-place hybrid radix/comparison algorithm much like integer_sort , but sorts IEEE floating-point numbers (positive, zero, NaN, and negative) into ascending order by casting them to integers.
You can use:
list1 = sorted(list1)
If it is in the second format (as a string) you can use the key parameter to convert it into floats by using:
list1 = sorted(list1, key=float)
The key parameter expects a function that will transform the values before sorting using the transformed values, but keeping the original values
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