Python:GQuery 结果集上的 DISTINCT(GQL、GAE) [英] Python: DISTINCT on GQuery result set (GQL, GAE)

查看:18
本文介绍了Python:GQuery 结果集上的 DISTINCT(GQL、GAE)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您在 Google App Engine 数据存储区中有一个实体,用于存储匿名用户的链接.您想执行以下不受支持的 SQL 查询:

SELECT DISTINCT user_hash FROM links

相反,您可以使用:

user = db.GqlQuery("SELECT user_hash FROM links")

如何使用 Python最有效地过滤结果,使其返回 DISTINCT 结果集?如何统计 DISTINCT 结果集?

解决方案

集合是解决这个问题的好方法:

<预><代码>>>>a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com']>>>b = 集合(a)>>>乙set(['livejournal.com', 'google.com', 'stackoverflow.com'])>>>

关于第一个答案的一个建议是,集合和字典更擅长快速检索唯一结果,列表中的成员资格是 O(n) 对其他类型的 O(1),所以如果你想存储额外的数据,或者做一些类似创建提到的 unique_results 列表的事情,这样做可能会更好:

unique_results = {}>>>对于 a 中的项目:unique_results[item] = ''>>>unique_results{'livejournal.com': '', 'google.com': '', 'stackoverflow.com': ''}

Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users. You would like to perform the following SQL query, which is not supported:

SELECT DISTINCT user_hash FROM links

Instead you could use:

user = db.GqlQuery("SELECT user_hash FROM links")

How to use Python most efficiently to filter the result, so it returns a DISTINCT result set? How to count the DISTINCT result set?

解决方案

A set is good way to deal with that:

>>> a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com']
>>> b = set(a)
>>> b
set(['livejournal.com', 'google.com', 'stackoverflow.com'])
>>> 

One suggestion w/r/t the first answer, is that sets and dicts are better at retrieving unique results quickly, membership in lists is O(n) versus O(1) for the other types, so if you want to store additional data, or do something like create the mentioned unique_results list, it may be better to do something like:

unique_results = {}
>>> for item in a:
    unique_results[item] = ''


>>> unique_results
{'livejournal.com': '', 'google.com': '', 'stackoverflow.com': ''}

这篇关于Python:GQuery 结果集上的 DISTINCT(GQL、GAE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆