Natural Order Sorting for Lists

  • Share this:

Code introduction


This function takes two lists and sorts them in a natural order, which means it arranges strings with mixed numbers and letters in a sequence that respects the natural order of numbers and letters.


Technology Stack : re, functools, operator

Code Type : Sort function

Code Difficulty : Intermediate


                
                    
def sorted_nicely(arg1, arg2):
    """
    This function takes two arguments and returns them sorted based on their natural order
    """
    from functools import cmp_to_key
    import operator

    def natural_keys(text):
        return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', text)]

    def cmp(x, y):
        return (natural_keys(x) > natural_keys(y)) - (natural_keys(x) < natural_keys(y))

    return sorted(arg1, key=cmp_to_key(cmp)), sorted(arg2, key=cmp_to_key(cmp))