如何计算列表python中的元素重复,django

Shi*_*dla 4 python django list count django-taggit

我有一个django应用程序,我正在使用django-taggit我的博客.

现在我有一个元素列表(实际上是对象),我在下面的一个视图中从数据库中获取

tags = [<Tag: some>, <Tag: here>, <Tag: tags>, <Tag: some>, <Tag: created>, <Tag: here>, <Tag: tags>]
Run Code Online (Sandbox Code Playgroud)

现在如何查找列表中每个元素的计数并返回元组列表,如下所示

结果应如下

[(<Tag: some>,2),(<Tag: here>,2),(<Tag: created>,1),(<Tag: tags>,2)]
Run Code Online (Sandbox Code Playgroud)

这样我就可以通过循环它来在模板中使用它们

视图

def display_list_of_tags(request):
    tags = [<Tag: some>, <Tag: here>, <Tag: tags>, <Tag: some>, <Tag: created>, <Tag: here>, <Tag: tags>]
    # After doing some operation on above list as indicated above
    tags_with_count =  [(<Tag: some>,2),(<Tag: here>,2),(<Tag: created>,1),(<Tag: tags>,2)]
    return HttpResponse('some_template.html',dict(tags_with_count:tags_with_count))
Run Code Online (Sandbox Code Playgroud)

模板

{% for tag_obj in tags_with_count %}
   <a href="{% url 'tag_detail' tag_obj %}">{{tag_obj}}</a> <span>count:{{tags_with_count[tag_obj]}}</span>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

如上所述如何计算列表中每个元素的出现次数?这个过程应该最终很快,因为我可能在标记应用程序中有数百个标签吗?

如果列表只包含字符串作为元素,我们可以使用类似的东西from collections import counter并计算计数,但在上述情况下如何做?

我的目的是计算出现的次数并将其打印在模板中,如tag object and occurences:

所以我正在寻找一种快速有效的方法来执行上述功能?

编辑:

所以我得到了所需的答案,我将结果发送到模板,将结果转换list of tuples为字典,如下所示

{<Tag: created>: 1, <Tag: some>: 2, <Tag: here>: 2, <Tag: tags>: 2}
Run Code Online (Sandbox Code Playgroud)

并试图通过以类似的格式循环它来打印上面的字典

{% for tag_obj in tags_with_count %}
       <a href="{% url 'tag_detail' tag_obj %}">{{tag_obj}}</a> <span>count:{{tags_with_count[tag_obj]}}</span>
    {% endfor %}
Run Code Online (Sandbox Code Playgroud)

但它显示以下错误

TemplateSyntaxError: Could not parse the remainder: '[tag_obj]' from 'tags_with_count[tag_obj]'
Run Code Online (Sandbox Code Playgroud)

那么如何通过键和值来显示django模板中的字典呢?

完成后我们可以更改上面的模板循环,如下所示

{% for tag_obj, count in tags_with_count.iteritems %}
Run Code Online (Sandbox Code Playgroud)

Gil*_*tes 6

试试Python的计数器:

from collections import Counter

l =  ['some', 'here', 'tags', 'some', 'created', 'here', 'tags']
print(Counter(l).items())
Run Code Online (Sandbox Code Playgroud)

输出:

[('created', 1), ('some', 2), ('here', 2), ('tags', 2)]
Run Code Online (Sandbox Code Playgroud)