Sorting List Elements by Index of Another List

  • Share this:

Code introduction


The function sorts elements from the first list according to their indices in the second list. If the indices of corresponding elements in the two lists are different, they are sorted according to the order of indices in the second list.


Technology Stack : Sorting

Code Type : Sort function

Code Difficulty : Intermediate


                
                    
def aordiff(arg1, arg2):
    if isinstance(arg1, list) and isinstance(arg2, list):
        return sorted(arg1, key=lambda x: arg2.index(x))
    else:
        raise ValueError("Both arguments must be lists")                
              
Tags: