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?
>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.')]