Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to sort list with float values [duplicate]

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.

like image 591
sathish Avatar asked May 19 '16 09:05

sathish


People also ask

Can you sort a float?

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.


1 Answers

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

like image 173
Jan van der Vegt Avatar answered Nov 15 '22 12:11

Jan van der Vegt