对列表进行排序但保持重复项的顺序

Sorting a list but keeping the order of duplicates

我必须根据有效期 (YYYYMMDD) 对我所有的项目进行排序,到期日期越早,项目应该越接近列表的末尾(reverse=True 的原因)和当到期日期相同时,我应该在接近末尾时添加一个(先进先出)。我尝试使用 sorted() 函数,正如您在这里看到的,结果与我想要的结果不同。

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]

有什么方法可以在这里使用 sorted() 函数,还是我必须做一些完全不同的事情?

您应该对颠倒的列表进行排序,这样最后一项将始终排在第一位:

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

或按顺序和反向排序:

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

输出:

[('20771023', 'RICE Unlimited'),
 ('20220921', 'G. P. a C.'),
 ('20220315', 'UniCORN & co.'),
 ('20220202', "Theorem's Rice"),
 ('20220202', 'ACME Rice Ltd.')]