20

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup

我可以想到几种使用循环的方法,但我特别想知道是否有一个整洁的单线。

4

3 回答 3

36

结合itertools.groupby得到operator.itemgetter一个很好的解决方案:

from operator import itemgetter
from itertools import groupby

key = itemgetter('gender')
iter = groupby(sorted(people, key=key), key=key)

for gender, people in iter:
    print '===', gender, '==='
    for person in people:
        print person
于 2009-01-25T15:43:26.363 回答
2

如果数据源(people在这种情况下)已经按键排序,则可以绕过sorted调用:

iter = groupby(people, key=lambda x:x['gender'])
for gender, people in iter:
    print '===', gender, '==='
    for person in people:
        print person

注意:如果sorted是普通字典,则不保证顺序;因此你必须打电话sorted。在这里,我假设这sorted是一种collections.OrderedDict或其他类型的有序数据结构。

于 2015-02-06T15:04:07.870 回答
1

以前的答案帮助我解决了我的问题。以供将来参考,如果您有一些嵌套数据,例如

{'city_name':'City1','comp_name':'Company1','name':'Branch1'}

并且您想按城市分组,然后按该城市的公司分组,例如:

City1
 Company 1
   Branch 1
   Branch 2
 Company 2
   Branch 1
 Company 3
   Branch 1
City2
 Company 2
   Branch 1
 Company 3
   Branch 1
   Branch 2
City3
 Company 1
   Branch 1
 Company 2
   Branch 1
   Branch 2

我通过这样做解决了它:

key = itemgetter('city_name')    
iter = groupby(queryset, key=key) # assuming queryset is already sorted by city_name

for key, group in iter:
    print(key)
    key2 = itemgetter('company_name')
    iter2 = groupby(sorted(group, key=key2), key=key2) # now we must sort by company_name
    for comp, branch in iter2:
        print(comp)
        for b in branch:
            print(b)
于 2015-06-08T04:34:08.243 回答