按值按价值排列日期词典列表

发布于 2025-01-24 10:33:20 字数 523 浏览 0 评论 0原文

我正在尝试将价值与当年分类。

本年度值应首先显示。

mdlist = [{0:'31 Jan 2022', 1:'', 2:'10 Feb 2022'},
          {0:'10 Feb 2021', 1:'20, Feb 2021', 2:''}, 
          {0:'10 Feb 2022', 1:'10 Feb 2022', 2:'10 Feb 2022'}]
mdlist = sorted(mdlist, key=lambda d:d[0])

但是它无法像预期的那样工作

mdlist = [{0:'31 Jan 2022', 1:'', 2:'10 Feb 2022'},
          {0:'10 Feb 2022', 1:'10 Feb 2022', 2:'10 Feb 2022'},
          {0:'10 Feb 2021', 1:'20 Feb 2021', 2:''}]

I'm trying to sort the values with current year.

Current year values should show first.

mdlist = [{0:'31 Jan 2022', 1:'', 2:'10 Feb 2022'},
          {0:'10 Feb 2021', 1:'20, Feb 2021', 2:''}, 
          {0:'10 Feb 2022', 1:'10 Feb 2022', 2:'10 Feb 2022'}]
mdlist = sorted(mdlist, key=lambda d:d[0])

but it is not working as expected

expected output:

mdlist = [{0:'31 Jan 2022', 1:'', 2:'10 Feb 2022'},
          {0:'10 Feb 2022', 1:'10 Feb 2022', 2:'10 Feb 2022'},
          {0:'10 Feb 2021', 1:'20 Feb 2021', 2:''}]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最笨的告白 2025-01-31 10:33:20

也许您可以通过使用dateTime模块来利用这些是数据的事实,并按照降序和按月升序按年来对其进行排序:

from datetime import datetime
def sorting_key(dct):
    ymd = datetime.strptime(dct[0], "%d %b %Y")
    return -ymd.year, ymd.month, ymd.day

mdlist.sort(key=sorting_key)

输出:输出:

[{0: '31 Jan 2022', 1: '', 2: '10 Feb 2022'},
 {0: '10 Feb 2022', 1: '10 Feb 2022', 2: '10 Feb 2022'},
 {0: '10 Feb 2021', 1: '20 Feb 2021', 2: ''}]

Maybe you could leverage the fact that these are datetimes by using the datetime module and sort it by the years in descending order and the month-days in ascending order:

from datetime import datetime
def sorting_key(dct):
    ymd = datetime.strptime(dct[0], "%d %b %Y")
    return -ymd.year, ymd.month, ymd.day

mdlist.sort(key=sorting_key)

Output:

[{0: '31 Jan 2022', 1: '', 2: '10 Feb 2022'},
 {0: '10 Feb 2022', 1: '10 Feb 2022', 2: '10 Feb 2022'},
 {0: '10 Feb 2021', 1: '20 Feb 2021', 2: ''}]
ゃ懵逼小萝莉 2025-01-31 10:33:20

使用函数返回0如果年度为20221否则。这将首先对所有2022日期进行排序。

firstyear = '2022'
mdlist = sorted(mdlist, key=lambda d: 0 if d:d[0].split()[-1] == firstyear else 1)

Use a key function that returns 0 if the year is 2022, 1 otherwise. This will sort all the 2022 dates first.

firstyear = '2022'
mdlist = sorted(mdlist, key=lambda d: 0 if d:d[0].split()[-1] == firstyear else 1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文