您应该将数据作为字典的排序列表传递给模板:
>>> data = [ ('panda','fiat'),
... ('500','fiat'),
... ('focus','ford') ]
>>>
>>> from itertools import groupby
# note that we need to sort data before using groupby
>>> groups = groupby(sorted(data, key=lambda x: x[1]), key=lambda x:x[1])
# make the generators into lists
>>> group_list = [(make, list(record)) for make, record in groups]
# sort the group by the number of car records it has
>>> sorted_group_list = sorted(group_list, key=lambda x: len(x[1]), reverse=True)
# build the final dict to send to the template
>>> sorted_car_model = [{'make': make, "model": r[0]} for (make, records) in sorted_group_list for r in records]
>>> sorted_car_model
[{'make': 'fiat', 'model': 'panda'}, {'make': 'fiat', 'model': '500'}, {'make': 'ford', 'model': 'focus'}]
此处的目标是对列表进行排序,以便汽车制造商按照他们生产的车型数量进行排名。
然后,使用:
{% regroup car_models by make as make_list %}
{% for item in make_list %}
{{ item.grouper }} ({{ item.list|length }}) <br>
{% endfor %}
要得到:
fiat 2
ford 1
参考:regroup
如果您的数据看起来像您在评论中的数据:
>>> car_models = [
... {'make': 'ford', 'model': 'focus'},
... {'make': 'fiat', 'model': 'panda'},
... {'make': 'ford', 'model': '500'},
... {'make': 'fiat', 'model': '500'},
... {'make': 'opel', 'model': '500'},
... {'make': 'opel', 'model': '500'},
... {'make': 'opel', 'model': '500'},
... ]
>>>
>>> groups = groupby(sorted(car_models, key=lambda x:x['make']), key=lambda x:x['make'])
>>> groups = [(make, list(x)) for make, x in groups]
>>> sorted_group_list = sorted(groups, key=lambda x:len(x[1]), reverse=True)
>>> sorted_car_model = [{'make': make, 'model': r['model']} for (make, records) in sorted_group_list for r in records]
>>> sorted_car_model
[{'make': 'opel', 'model': '500'}, {'make': 'opel', 'model': '500'}, {'make': 'opel', 'model': '500'}, {'make': 'fiat', 'model': 'panda'}, {'make': 'fiat', 'model': '500'}, {'make': 'ford', 'model': 'fo
cus'}, {'make': 'ford', 'model': '500'}]
或者,您可以将结果传递给模板,如下所示:
>>> from collections import Counter
>>> l = [r['make'] for r in car_models]
>>> c = Counter(l)
>>> result = [{k: v} for k,v in dict(c).iteritems()]
>>> result = sorted(result, key=lambda x: x.values(), reverse=True)
[{'opel': 3}, {'fiat': 2}, {'ford': 2}]
然后,将此结果传递给模板并简单地渲染结果:
{% for r in result %}
{% for k,v in r.items %}
{{ k }} {{ v }}
{% endfor %}j
{% endfor %}
然后你会得到:
opel 3
fiat 2
ford 2