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

Time:11-18

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.

CodePudding user response:

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)

CodePudding user response:

Try this

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


def sortList(inputList):
    masterList = [[value, index] for index, value in enumerate(inputList)]
    masterList.sort()

    values = []
    indices = []
    for item in masterList:
        values.append(item[0])  # get the item
        indices.append(item[1])  # get the index
    return values, indices


sortedData = []
sortedIndices = []
for subList in data:
    sortedList, indices = sortList(subList)
    sortedData.append(sortedList)
    sortedIndices.append(indices)


print(sortedData)
print(sortedIndices)
  • Related