+

Python | Methods for Sorting a List of Floating Point Values

Examples :

  Input:  list = [`1.2`,` .8`, `19.8`,` 2.7`, `99.8 `,` 80.7`]  Output:  [`.8`,` 1.2`, `2.7`,` 19.8`, `80.7`,` 99.8`]  Input:  list = [12.8, .178, 1.8, 782.7, 99.8, 8.7]  Output:  [0.178, 1.8, 8.7, 12.8, 99.8, 782.7] 

Let`s discuss different solutions this problem.

Method # 1: Using lambda

# Python code for sorting a list of decimal values

 
# Initialization list

Input =   [ 12.8 ,. 178 , 1.8 , 782.7 , 99.8 , 8.7 ]

 
# Using sorting and lambda

Output = sorted ( Input , key = lambda x: float (x))

 
# Printout

print (Output)

Output:

 [0.178, 1.8, 8.7, 12.8, 99.8, 782.7] 

Method # 2: Use title sorted

# Python code for sorting a list of decimal values ​​

 
# Initialization list

Input =   [ 12.8 ,. 178 , 1.8 , 782.7 , 99.8 , 8.7 ]

 
# Using sorted + key

Output = sorted ( Input , key = float )

 
# Printout

print (Output)

Output:

 [0.178, 1.8, 8.7, 12.8, 99.8, 782.7] 

Method # 3: Using Sort

# Python code to sort the list of decimal values ​​

 
# Initialization list

Input =   [ 12.8 ,. 178 , 1.8 , 782.7 , 99.8 , 8.7 ]

 
# Using sorting + key

Input . sort (key = float )

 
# Printout

print ( Input )

Exit:

 [0.178, 1.8, 8.7, 12.8, 99.8, 782.7] 
Get Solution for free from DataCamp guru