Example :
Input: lst = [[’Machine’,’ London’, ’Canada’,’ France’], [ ’Spain’,’ Munich’], [’Australia’,’ Mandi’]] Output: flist = [[’Canada’,’ France’, ’London’,’ Machine’], [ ’Munich’,’ Spain’], [’Australia’,’ Mandi’]]
There are several ways to sort each list alphabetically.
Method # 1: Map Usage
# Python code to sort all sublists # in this list of strings # Initialization list Input = [[ ’Machine’ , ’ London’ , code> ’Canada’ , ’ France’ , ’ Lanka’ ], [ ’ Spain’ , ’Munich’ ], [ ’Australia’ , ’ Mandi’ ]] # Using the map for sorting Output = list ( map ( sorted , Input )) # Printout print (Output) |
Exit:
[[’Canada ’,’ France ’,’ Lanka ’,’ London ’,’ Machine ’], [’ Munich ’,’ Spain ’], [’ Australia ’,’ Mandi ’]]
Method # 2: Using lambda and sorting
# Python code to sort all sublists # in this list of strings # Initialization list Input = [[ ’Machine’ , ’ London’ , ’Canada’ , ’France’ , ’Lanka’ ], [ ’Spain’ , ’ Munich’ ], [ ’ Australia’ , ’Mandi’ ]] # using lambda and sorted Output = [ sorted (x, key = lambda x: x [ 0 ]) for x in Input ] # Printout print (Output) |
Exit:
[ [’Canada’, ’France’, ’London’, ’Lanka’, ’Machine’], [’Munich’, ’Spain’], [’Australia’, ’Mandi’]]
Method # 3: Using iteration and sorting
# Python code to sort all sublists # in this list of lines # Initialization list Input = [[ ’Machine’ , ’London’ , ’ Canada’ , ’ France’ , ’Lanka’ ], [ ’Spain’ , ’ Munich’ ] , [ ’Australia’ , ’Mandi’ ]] # with Sublist editing for sublist in Input : sublist.sort () # Output to print print ( Input ) |
Output:
[[’Canada’, ’France’, ’Lanka’, ’London’, ’Machine’], [’Munich’, ’Spain’], [’Australia’, ’Mandi ’]]
Python | Sort all sublists in a given list of strings Python functions: Questions
Python | Sort all sublists in a given list of strings String Variables: Questions