You need to enable JavaScript to run this app. 如何按指定键过滤Python字典列表并按datetime倒序排序?
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定键过滤Python字典列表并按datetime倒序排序?

实现方法

实现逻辑分为两步,可读性和可维护性都更好:

  • 第一步:通过列表推导式过滤出满足action=1条件的字典项
  • 第二步:用内置sorted()方法对过滤后的结果按date字段排序,设置reverse=True参数即可让时间最新的条目排在最前面

完整可运行代码

from datetime import datetime

# 原始动作列表
actions = [
    {'action':1,'date':datetime(2021, 3, 28, 8, 57, 29, 734261)},
    {'action':2,'date':datetime(2021, 3, 28, 18, 57, 29, 734261)},
    {'action':1,'date':datetime(2021, 3, 29, 20, 57, 29, 734261)}
]

# 过滤出action=1的条目
filtered_actions = [item for item in actions if item['action'] == 1]

# 按date字段降序排序,最新时间排首位
sorted_result = sorted(filtered_actions, key=lambda item: item['date'], reverse=True)

运行输出

执行完成后sorted_result的具体内容为:

[
{'action': 1, 'date': datetime(2021, 3, 29, 20, 57, 29, 734261)},
{'action': 1, 'date': datetime(2021, 3, 28, 8, 57, 29, 734261)}
]

如果追求代码简洁,也可以将过滤和排序逻辑合并为单行写法:

sorted_result = sorted(
    [item for item in actions if item['action'] == 1],
    key=lambda x: x['date'],
    reverse=True
)

内容的提问来源于stack exchange,提问作者emir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 04:45:08