简体   繁体   English

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

[英]How to count the repetition of the elements in a list python, django

I have a django app, I am using django-taggit for my blog.我有一个 django 应用程序,我在我的博客中使用django-taggit

Now I have a list of elements (In fact objects) that I got from database in one of my view as below现在我有一个从数据库中获得的元素列表(实际上是对象),如下所示

tags = [<Tag: some>, <Tag: here>, <Tag: tags>, <Tag: some>, <Tag: created>, <Tag: here>, <Tag: tags>]

Now how to find the count of each element in the list and return a list of tuples as below现在如何找到列表中每个元素的计数并返回一个元组列表,如下所示

result should be as below结果应该如下

[(<Tag: some>,2),(<Tag: here>,2),(<Tag: created>,1),(<Tag: tags>,2)]

so that I can use them in template by looping it something like below这样我就可以通过像下面这样循环它在模板中使用它们

view看法

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))

template模板

{% 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 %}

so as described above how to count the occurences of each element in the list?所以如上所述如何计算列表中每个元素的出现次数? The process should be ultimately fast, because I may have hundreds of tags in the tagging application right?这个过程最终应该很快,因为我在标记应用程序中可能有数百个标记,对吗?

If the list contains only strings as elements, we could use something like from collections import counter and calculate the count, but how do do in the above case ?如果列表只包含字符串作为元素,我们可以使用from collections import counter类的东西并计算计数,但在上述情况下怎么办?

All my intention is to count the occurrences and print them in the template like tag object and occurrences ,我的所有目的是计算出现次数并将它们打印在模板中,如tag object and occurrences

So I am searching for a fast and efficient way to perform above functionality?所以我正在寻找一种快速有效的方法来执行上述功能?

Edit :编辑

So I got the required answer from and I am sending the result to template by converting the resultant list of tuples to dictionary as below所以我得到了所需的答案,并通过将结果list of tuples转换为字典将结果发送到模板,如下所示

{<Tag: created>: 1, <Tag: some>: 2, <Tag: here>: 2, <Tag: tags>: 2}

and tried to print the above dictionary by looping it in the format like并尝试通过以如下格式循环来打印上述字典

{% 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 %}

But its displaying the below error但它显示以下错误

TemplateSyntaxError: Could not parse the remainder: '[tag_obj]' from 'tags_with_count[tag_obj]'

So how to display the dictionary in the django templates by like key and value?那么如何在django模板中通过like key和value来显示字典呢?

Done we can change the above template looping as below完成我们可以改变上面的模板循环如下

{% for tag_obj, count in tags_with_count.iteritems %}

Try Python's Counter :试试 Python 的计数器

from collections import Counter

l =  ['some', 'here', 'tags', 'some', 'created', 'here', 'tags']
print(Counter(l).items())

Output:输出:

[('created', 1), ('some', 2), ('here', 2), ('tags', 2)]

Try something like:尝试类似:

x = ['raz', 'dwa', 'raz', 'trzy', 'dwa', 'raz', 'trzy', 'cztery']
wynik = {}
for i in x:
    if i in wynik:
         wynik[i] += 1
    else:
         wynik[i] = 1
print wynik

{'cztery': 1, 'dwa': 2, 'raz': 3, 'trzy': 2}

and, if you need:并且,如果您需要:

import operator
wynik_sorted = sorted(wynik.iteritems(), key=operator.itemgetter(1), reverse=True)

print wynik_sorted
[('raz', 3), ('dwa', 2), ('trzy', 2), ('cztery', 1)]

The count and set functions look like they'd be of use here. countset函数看起来在这里很有用。

>>> l = ["i", "i", "am", "am", "am", "test"]
>>> list(set([(a, l.count(a)) for a in l]))
[('test', 1), ('i', 2), ('am', 3)]

l.count() provides the number of occurrences of the given item in the list. l.count()提供给定项目在列表中出现的次数。 set() turns the list into a set (an unordered collection containing no duplicate items) and then list converts that set back to the proper type. set()将列表转换为一个集合(一个不包含重复项的无序集合),然后list将该集合转换回正确的类型。

Since you're dealing with Tag objects, it's possible that you'd need to use some method to get their string representations (although I can't find documentation on their interface).由于您正在处理Tag对象,因此您可能需要使用某种方法来获取它们的字符串表示形式(尽管我无法在其界面上找到文档)。 Maybe something like this:也许是这样的:

>>> l = [a.text for a in l]
>>> list(set([(a, l.count(a)) for a in l]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM