与 Django 的“重新组合"模板标签等价的惯用 Python 是什么? [英] What's the idiomatic Python equivalent to Django's 'regroup' template tag?

查看:21
本文介绍了与 Django 的“重新组合"模板标签等价的惯用 Python 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我可以想到几种用循环来做的方法,但我特别想知道是否有一个简洁的单行.

I can think of a few ways of doing it with loops but I'd particularly like to know if there is a neat one-liner.

推荐答案

Combine itertools.groupbyoperator.itemgetter 得到一个很好的解决方案:

Combine itertools.groupby with operator.itemgetter to get a pretty nice solution:

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

这篇关于与 Django 的“重新组合"模板标签等价的惯用 Python 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆