Sort a mixed list in Python

Python Methods and Functions

Method # 1: Using sort () + comparator

This problem can be solved using the sort function provided by Python. We can create our own comparator to do the mixed sorting task.

# Python3 code to demonstrate how it works
# Sort the mixed list
# using sort () + comparator

  
# comparison function for sorting

def mixs (num):

  try :

  ele = int (num)

return ( 0 , ele, `)

  except ValueError:

return ( 1 , num,` `)

 

 
# initialize the list

test_list = [ 4 , ` gfg` , 2 , `best` , `is` , 3 ]

  
# print original list

print ( "The original list:" + str (test_list))

 
# Sort the mixed list
# using sort () + comparator

test_list. sort (key = mixs)

 
# print result

print ( "List after mixed sorting:" + str (test_list))

Output: < / p>

 The original list: [4, `gfg`, 2,` best`, `is`, 3] List after mixed sorting: [2, 3, 4,` best`, `gfg`,` is`] 

Method # 2: Using sorted () + key + lambda + isdigit ()

A combination of the above functionality can also be used to achieve a solution to this problem. In this, we are simply sorting the list using sorted () using key functions, using a lambda function to separate the digits using isdigit ().

# Python3 code to demonstrate how it works
# Sort the mixed list
# using sorted () + key + lambda + isdigit ()

 
# initialize the list

test_list = [ ` 4` , `gfg` , `2` , ` best` , `is` , `3` ]

  
# print original list

print ( "The original list:" + str (test_list))

  
# Sort the mixed list
# using sorted () + key + lambda + isdigit ()

res = sorted (test_list, key = lambda ele: ( 0 , int (ele))

  if ele.isdigit () else ( 1 , ele))

 
# print result

print ( "List after mixed sorting:" + str (res))

Output:

 The original list: [`4`,` gfg`, `2`,` best`, `is`,` 3`] List after mixed sorting: [`2`,` 3`, `4`,` best`, `gfg`,` is`] 




Get Solution for free from DataCamp guru