Natural Sorting of Tuple List

  • Share this:

Code introduction


This function sorts a list of tuples in a natural order, similar to a telephone directory.


Technology Stack : re

Code Type : Function

Code Difficulty : Intermediate


                
                    
def sorted_natural_keys(lst):
    """
    Sorts a list of tuples in a natural way (like a telephone directory).
    """
    convert = lambda text: int(text) if text.isdigit() else text.lower()
    alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
    return sorted(lst, key=alphanum_key)                
              
Tags: