  Python | Sort a tuple by float element

Python Methods and Functions

Examples:

Input: tuple = [('lucky',' 18.265'), ('nikhil',' 14.107'), ('akash',' 24.541'), ('anand ',' 4.256'), ('gaurav',' 10.365')] Output: [('akash',' 24.541'), ('lucky',' 18.265'), ('nikhil',' 14.107'), ('gaurav',' 10.365'), ('anand',' 4.256')] Input: tuple = [('234',' 9.4'), ('543',' 16.9'), ('756', '5.5'), (' 132', '4.2'), (' 342', '7.3')] Output: [(' 543', '16.9'), (' 234', '9.4'), (' 342', '7.3'), (' 756', '5.5'), (' 132', '4.2')]

We can understand this from the image below:

Method 1: Using the

# Python code for sorting tuples using the float element
# Sort function with using sorted ()

def Sort (tup):

# reverse = True

Key # set to sort using floating point elements

# lambda was used

return ( sorted (tup, key = lambda x: float (x [ 1 ]), reverse = True ))

Driver code

tup = [( 'lucky' , '18.265' ), ( ' nikhil' , '14.107' ), ( 'akash' , ' 24.541' ),

( 'anand' , '4.256' ), ( ' gaurav ' , ' 10.365' )]

print (Sort (tup))

< / tr>

Output:

[('akash',' 24.541'), ('lucky', '18.265'), (' nikhil', '14.107'), (' gaurav', '10.365'), (' anand', '4.256')]

Method 2 : a way to sort in place using sort ():

When sorting with this method, the actual contents of the tuple are changed, while in the previous method the contents of the original tuple remained the same.

 # Python code for sorting tuples using the float element # Internal sorting using sort () def Sort (tup): # reverse = True Cl yuch # set to sort using floating point elements # lambda was used tup.sort (key = lambda x: float ( x [ 1 ]), reverse = True ) print (tup)    Driver code tup = [( 'lucky' , ' 18.265'  ), ( 'nikhil' , '14.107' ), ( ' akash' , '24.541' ),    ( 'anand' , ' 4.256' ), ( 'gaurav' , '10.365' )] Sort (tup)

Output:

[('akash', '24.541'), (' lucky', '18.265'), (' nikhil', '14.107'), (' gaurav', '10.365'), (' anand', '4.256')]