【问题标题】:List - How to find number of times an item appears [duplicate]列表 - 如何查找项目出现的次数[重复]
【发布时间】:2012-07-31 23:41:33
【问题描述】:

可能重复:
How to calculate the occurrences of a list item in Python?

我正在进行一项民意调查。为此,我正在使用 Python,而我被困在的部分是试图弄清楚如何计算某件事的次数,比如“General Store”出现。

例如投票:

您在哪里看到的广告最多?

  1. 杂货店

  2. 超市

  3. 商城

  4. 小店

如果需要该信息,则通过单选按钮提交投票数据。所有这些答案都将附加到一个列表中,然后我想创建一个结果页面,显示每件事的投票次数。

【问题讨论】:

    标签: python


    【解决方案1】:

    首先,我要说的是,您可能为投票结果问题使用了错误的解决方案。为什么不为每个选项保留一个计数器,这样一来,您的文件或您用来存储这些数据的任何后端都不会随着响应的到来而线性增长。

    这样做会更容易,因为无论如何您都将创建计数器,唯一的区别是每次加载响应页面时您都必须计算所有项目。

    #initializing a variable with some mock poll data
    option1 = "general store"
    option2 = "supermarket"
    option3 = "mall"
    option4 = "small store"
    
    sample_data = [option1,option2,option1,option1,option3,option3,option4,option4,option4,option2]
    
    #a dict that will store the poll results
    results = {}
    
    for response in sample_data:
        results[response] = results.setdefault(response, 0) + 1
    

    现在,结果会将列表中出现的每个字符串作为键,并将它出现的次数作为它的值。

    【讨论】:

      【解决方案2】:

      对于 Python 2.7+,您可以使用collections.Counter

      >>> from collections import Counter
      >>> l = ['hello','hello','hello','there','foo','foo','bar']
      >>> Counter(l).most_common()
      [('hello', 3), ('foo', 2), ('there', 1), ('bar', 1)]
      

      如果您不在 2.7 上,则可以改为:

      >>> s = set(l)
      >>> d = {}
      >>> for i in s:
      ...    d[i] = l.count(i)
      ... 
      >>> d
      {'there': 1, 'bar': 1, 'hello': 3, 'foo': 2}
      

      【讨论】:

      【解决方案3】:

      这行得通:

      >>> from collections import Counter
      >>> data = ['Store', 'Office', 'Store', 'Office', 'Home', 'Nowhere']
      >>> Counter(data)
      Counter({'Office': 2, 'Store': 2, 'Home': 1, 'Nowhere': 1})
      

      【讨论】:

        【解决方案4】:

        如果你有清单,你可以做

        ls = ["Mall", "Mall", "Supermarket"]
        ls.count("Mall")
        >>> 2
        ls.count("General Store")
        >>> 0
        

        【讨论】:

          【解决方案5】:

          你会想要使用collections.Counter

          还有.most_common 方法。

          【讨论】:

          • 需要注意的是,这只适用于 Python 2.7+
          • @BurhanKhalid 该链接解释了这一点,并包含适用于 Py 2.5 的代码的链接
          猜你喜欢
          • 2011-10-22
          • 2020-12-03
          • 1970-01-01
          • 2020-04-19
          • 2023-03-19
          • 1970-01-01
          • 2011-10-16
          • 2013-09-30
          相关资源
          最近更新 更多