You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中验证条件后按activity_created_on倒序获取activity_message

解决按创建时间倒序筛选并获取消息的问题

你当前的代码用set存储结果,而集合本身是无序且自动去重的,完全没法实现按activity_created_on倒序输出的需求。要达成「后创建的条目优先输出」的目标,得换用列表存储,再加上排序逻辑。

样本数据

user_id = 1
project_id = 2
a = [{
            "_id": {
                "$oid": "63fda80f3ab1f908c146131d"
            },
            "data": {
                "project_id": 2,
                "user_id": 1,
                "activity_message": "Success 1",
                "activity_created_on": {
                    "$date": "2023-02-28T12:30:55.652Z"
                }
            }
    },{
            "_id": {
                "$oid": "63fda80f3ab1f908c146131d"
            },
            "data": {
                "project_id": 2,
                "user_id": 1,
                "activity_message": "Success 2",
                "activity_created_on": {
                    "$date": "2023-02-28T12:36:55.652Z"
                }
            }
    }]

修正后的代码

def get_sorted_messages(a):
    # 先筛选符合条件的条目,同时保留创建时间用于排序
    filtered_items = []
    for item in a:
        data = item.get('data')
        if data and data["user_id"] == user_id and data["project_id"] == project_id:
            # 把消息和创建时间打包存入列表
            filtered_items.append({
                "message": data["activity_message"],
                "created_on": data["activity_created_on"]["$date"]
            })
    
    # 按创建时间倒序排序(ISO格式的时间字符串可以直接比较)
    sorted_items = sorted(filtered_items, key=lambda x: x["created_on"], reverse=True)
    
    # 提取排序后的消息
    return [item["message"] for item in sorted_items]

print(get_sorted_messages(a))

输出结果

运行后会得到:

['Success 2', 'Success 1']

关键改动说明

  • 放弃用set,改用列表存储筛选后的条目,保留排序所需的时间字段
  • 使用sorted()函数,通过key指定按创建时间排序,reverse=True实现倒序(最新的在前)
  • 最后提取排序后的消息返回,保证顺序符合要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:45:17