pythonlistnested-lists

How to sort two nested list which are linked by indexes


I am trying to sort a nested list by date (which I can). Then if the list has duplicate dates, sort the duplicate dates by time.

The first part of the list is the date or time, second part is the index.

Same index in both lists means they belong with each other:

I can sort one of the lists at a time like this:

index_list = []
for _, index in date_list:
    index_list.append(index)

The index_list is:

[0, 1, 2]

But index 1 & 2 should actually be swapped in this case because these are the lists:

date_list = [[b'05-07-2024', 0], [b'16-08-2024', 1], [b'16-08-2024', 2]]
time_list = [[b'15-20-55', 2], [b'15-21-00', 0], [b'23-41-01', 1]]

In the end I need a list of the indexes of the right order.

In this case that would be:

[0, 2, 1]

Solution

  • Combine date and time into a datetime object, then you can simply sort by it.

    from datetime import datetime
    
    sorted_indexes = sorted(
        [idx for date, idx in date_list],
        key=lambda idx: datetime.strptime(
            f"{date_list[idx][0].decode('utf-8')} {next(t[0] for t in time_list if t[1] == idx).decode('utf-8')}",
            '%d-%m-%Y %H-%M-%S'
        )
    )
    

    Output:

    [0, 2, 1]