什么是惯用的Python相当于Django的'重新组合'模板标签?

时间:2009-01-25 15:29:44

标签: python django django-templates

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

我可以想到一些用循环做的方法,但我特别想知道是否有一个整齐的单行。

3 个答案:

答案 0 :(得分:30)

itertools.groupbyoperator.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

答案 1 :(得分:1)

以前的答案帮助我解决了我的问题。备查, 如果您有一些嵌套数据,如

  

{' city_name':' City1',' comp_name':' Company1',' name':& #39;分支1'}

你希望按城市分组,然后按公司在该城市分组:

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)

答案 2 :(得分:0)

如果数据源(在这种情况下为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。我假设sortedcollections.OrderedDict或其他类型的有序数据结构。