你應該通過你的數據的模板類型的字典排序列表:
>>> 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
Referece: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
感謝imom0。你確定沒有更好的解決方案嗎?如果沒有生病必須接受你的.. – YardenST
@YardenST對不起,我不確定,但「完成勝過知府」。如果你使用'dictsort',參數必須是字典的關鍵。 – iMom0