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

Sorting a list but keeping the order of duplicates

I have to sort all my items according to their expiry date (YYYYMMDD), the sooner the expiry date, the closer to the end of the list the item should be (the reason for reverse=True) and when the expiry date is the same, i should have the one that was added sooner closer to the end (FIFO). I tried using the sorted() function, and as you can see here, the result is different from my desired result.

a = "20220202", "ACME Rice Ltd."
b = "20220315", "UniCORN & co."
c = "20771023", "RICE Unlimited"
d = "20220921", "G. P. a C."
e = "20220202", "Theorem's Rice"

lst = [a, b, c, d, e]

lst = sorted(lst, reverse=True, key=lambda x: x[0])

lst_output = [c, d, b, a, e]
lst_desired_output = [c, d, b, e, a]

Is there any way to use the sorted() function here, or do i have to do something completely else?

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

>Solution :

You should sort the reversed list, thus the last item will always be first:

sorted(reversed(lst), reverse=True, key=lambda x: x[0])

or sort in order and reverse:

sorted(lst, key=lambda x: x[0])[::-1]
# list(reversed(sorted(lst, key=lambda x: x[0])))

output:

[('20771023', 'RICE Unlimited'),
 ('20220921', 'G. P. a C.'),
 ('20220315', 'UniCORN & co.'),
 ('20220202', "Theorem's Rice"),
 ('20220202', 'ACME Rice Ltd.')]
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