Python how to sort a list with float values

How to sort a python list that contains float values,

list1 = [1, 1.10, 1.11, 1.1, 1.2] 

or

list1 = ['1', '1.10', '1.11', '1.1', '1.2'] 

Expected results: list_val = ['1', '1.1', '1.2' , '1.10', '1.11'], but the returned result using the 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 be between "1.1" and "1.10".

+4
source share
4 answers

You can use:

list1 = sorted(list1)

( ), :

list1 = sorted(list1, key=float)

, ,

+9

.

  • :: ,

    x=[1,2,3.1,4.5,2.3]
    y = sorted(x)
    y = sorted(x,key=float) #in case if the values were there as string.
    

    x - [1,2,3,1,4,5,2,3], , , .. [1,2,2,3,3,1,4,5], .

  • ::

    x=[1,2,3.1,4.5,2.3]
    x.sort()
    

    x , , x, [1,2,2,3,3,1,4,5].

.

, . :)

+1

Just use sorted:

sorted(list1, key=float)

This will convert the element to floatbefore comparison, so it will work for both a list of strings and a list of floats (or ints, for what it's worth).

0
source

Use the sort () method.

list1.sort()
print(list1)
-1
source

All Articles