按多个对象属性过滤对象列表

2024-09-30 22:10:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用ndbapi构建一个googleappengine应用程序(python2.7)。我是python开发新手,有一种感觉,这是一个以前已经回答过的问题,但是通过我的搜索,我无法找到类似于这个问题/解决方案的东西。我决定在这里提出我的问题。在

我有一个文档模型类,我需要查询并获取最“当前”的文档。具体地说,我想获得一个文档对象(实体)的列表,这些对象具有不同的文档名称,并且其expiration日期(一个datetime.date对象)是最大的值。在

例如,按到期日期降序查询文档,例如:

documents = Document.query().order(-Document.expiration).fetch()

退货:

^{pr2}$

基于这些查询结果,我想删除第二个(较旧)出现的“DocumentA”并得到如下结果:

[{"name": "DocumentC", "expiration": datetime.date(2015, 3, 1)},
 {"name": "DocumentA", "expiration": datetime.date(2014, 4, 1)},
 {"name": "DocumentB", "expiration": datetime.date(2014, 2, 15)}]

我的解决方案是:

def current_docs(docs):
    output = []
    for d in docs:
        if not any(o['name'] == d['name'] for o in output):
            output.append(d)
    return output

cd = current_docs(documents)
# returns:
# [{'expiration': datetime.date(2015, 3, 1), 'name': 'DocumentC'},
# {'expiration': datetime.date(2014, 4, 1), 'name': 'DocumentA'},
# {'expiration': datetime.date(2014, 2, 15), 'name': 'DocumentB'}]

这似乎给了我预期的结果,但是:

  1. 有没有更好的方法过滤原始查询以从一开始就得到我想要的结果?在
  2. 如果没有,有没有比我的解决方案更好、更有效的方法?在

Tags: 对象name文档docsoutputdatetimedatecurrent
2条回答

我对你第二个问题的回答是:

def current_docs(docs):
  tmp = {}
  output = []
  for d in docs:
    if d['name'] in tmp:
      continue
    tmp[d['name']] = 1
    output.append(d)
  return output

保存一个已经添加的名字的字典,只添加那些还没有添加的名字。但对谷歌应用引擎一无所知:)

如果您的数据满足文档中提到的限制,那么您应该能够使用投影查询和group_by=["name"]和{}来完成这项工作。在

或者,我建议将数据保存到一个预计算的表中,该表只包含唯一的文档名和它的最新数据/状态。在写入时会产生额外的开销,但是读取速度很快,而且不必依赖于未过滤的数据集,如果您打算在运行时进行过滤,那么这是必需的。在

相关问题 更多 >