http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
我可以想到几种使用循环的方法,但我特别想知道是否有一个整洁的单线。
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
我可以想到几种使用循环的方法,但我特别想知道是否有一个整洁的单线。
结合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
如果数据源(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
或其他类型的有序数据结构。
以前的答案帮助我解决了我的问题。以供将来参考,如果您有一些嵌套数据,例如
{'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)