我有一个django应用程序,我正在为我的博客使用django-taggit。在
现在我有一个元素列表(事实上是对象),我从数据库中得到了一个视图,如下所示tags = [, , , , , , ]
现在如何找到列表中每个元素的计数并返回元组列表,如下所示
结果如下
^{pr2}$
这样我就可以在模板中使用它们,就像下面这样循环
查看def display_list_of_tags(request):
tags = [, , , , , , ]
# After doing some operation on above list as indicated above
tags_with_count = [(,2),(,2),(,1),(,2)]
return HttpResponse('some_template.html',dict(tags_with_count:tags_with_count))
模板{% for tag_obj in tags_with_count %}
{{tag_obj}} count:{{tags_with_count[tag_obj]}}
{% endfor %}
如上所述,如何统计列表中每个元素的出现次数?
这个过程最终应该很快,因为我在标记应用程序中可能有数百个标记,对吗?在
如果列表只包含字符串作为元素,我们可以使用类似于from collections import counter的方法来计算计数,但是在上面的情况下怎么做呢?在
我的目的是统计出现的次数,然后在模板中打印出来,比如tag object and occurrences
所以我正在寻找一种快速有效的方法来执行上述功能?在
编辑:
所以我从
我通过将结果list of tuples转换为字典,将结果发送到模板,如下所示{: 1, : 2, : 2, : 2}
并尝试以如下格式循环打印上面的字典{% for tag_obj in tags_with_count %}
{{tag_obj}} count:{{tags_with_count[tag_obj]}}
{% endfor %}
但它显示了以下错误TemplateSyntaxError: Could not parse the remainder: '[tag_obj]' from 'tags_with_count[tag_obj]'
那么如何通过like key和value在django模板中显示字典呢?在
完成我们可以改变上面的模板循环如下{% for tag_obj, count in tags_with_count.iteritems %}