假设您在数据存储中有一个实体,为匿名用户存储链接。您希望执行以下不支持的SQL查询:
SELECT DISTINCT user_hash FROM links相反,您可以使用:
user = db.GqlQuery("SELECT user_hash FROM links")如何最有效地使用Python来过滤结果,从而返回一个不同的结果集?如何计算不同的结果集?
发布于 2008-10-27 08:25:57
一个集合是处理这个问题的好方法:
>>> a = ['google.com', 'livejournal.com', 'livejournal.com', 'google.com', 'stackoverflow.com']
>>> b = set(a)
>>> b
set(['livejournal.com', 'google.com', 'stackoverflow.com'])
>>> 第一个建议w/r/t是,集合和数据集更擅长快速检索唯一结果,对于其他类型,列表中的成员资格为O(n)与O(1),因此,如果您想存储其他数据,或执行创建上述unique_results列表之类的操作,则可能最好执行以下操作:
unique_results = {}
>>> for item in a:
unique_results[item] = ''
>>> unique_results
{'livejournal.com': '', 'google.com': '', 'stackoverflow.com': ''}发布于 2013-01-05 07:38:24
发布于 2008-10-27 08:01:47
一种选择是将结果放入set对象中:
http://www.python.org/doc/2.6/library/sets.html#sets.Set
结果集将只包含传递给它的不同值。
否则,构建一个只包含唯一对象的新列表就可以了。类似于:
unique_results = []
for obj in user:
if obj not in unique_results:
unique_results.append(obj)这个for循环也可以浓缩成一个列表理解。
https://stackoverflow.com/questions/239258
复制相似问题