http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
我可以想到几种使用循环的方法,但是我特别想知道是否有一个整齐的单缸纸。
结合itertools.groupby使用operator.itemgetter可获得不错的解决方案:
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