Python: DISTINCT on GQuery result set (GQL, GAE)

前端 未结 4 802
南方客
南方客 2020-12-10 16:34

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:<

4条回答
  •  盖世英雄少女心
    2020-12-10 17:01

    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': ''}
    

提交回复
热议问题