Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • [b'05-07-2024', 0] belongs with [b'15-21-00', 0]
  • [b'16-08-2024', 1] belongs with [b'23-41-01', 1]

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading