Search code examples
pythonsortingnested-lists

Sorting a list of lists by every list and return the final index


I want to sort a list with an arbitrary number of lists inside to sort by each of said lists. Furthermore I do not want to use any libraries (neither python-native nor 3rd party).

data = [['a', 'b', 'a', 'b', 'a'], [9, 8, 7, 6, 5]]

I know I can achieve this by doing

list(zip(*sorted(zip(*data))))
#  [('a', 'a', 'a', 'b', 'b'), (5, 7, 9, 6, 8)]

but I would like to have the sorting-index of that very process. In this case:

index = [4, 2, 0, 3, 1]

I found several answers for a fixed number of inside lists, or such that only want to sort by a specific list. Neither case is what I am looking for.


Solution

  • Add a temporary index list to the end before sorting. The result will show you the pre-sorted indices in the appended list:

    data = [['a', 'b', 'a', 'b', 'a'], [9, 8, 7, 6, 5]]
    assert all(len(sublist) == len(data[0]) for sublist in data)
    data.append(range(len(data[0])))
    *sorted_data, indices = list(zip(*sorted(zip(*data))))
    
    print(sorted_data)
    # [('a', 'a', 'a', 'b', 'b'), (5, 7, 9, 6, 8)]
    
    print(indices)
    # (4, 2, 0, 3, 1)