Sorting Tuples Based on Alphabetic Order and Alphabeticality

  • Share this:

Code introduction


This function accepts two lists as input and returns a sorted list where each element is a tuple containing two elements from the input lists. The sorting is based on two conditions: first by the alphabetical order of the first element, and then by the difference between whether the first element is alphabetical or not.


Technology Stack : Sorting, list comprehensions, lambda functions

Code Type : Sort function

Code Difficulty : Intermediate


                
                    
def aordiff(arg1, arg2):
    def alpha_sort_key(item):
        return item[0].isalpha()

    def diff_key(item):
        return item[1] - item[0].isalpha()

    try:
        if arg1 and arg2:
            return sorted(zip(arg1, arg2), key=lambda x: (x[0], x[1] - x[0].isalpha()))
        else:
            return None
    except TypeError:
        return None