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