【问题标题】:How do I count the occurrences of a list item?如何计算列表项的出现次数?
【发布时间】:2011-02-05 17:03:02
【问题描述】:

给定一个项目,我如何计算它在 Python 列表中出现的次数?

【问题讨论】:

    标签: python list count


    【解决方案1】:

    如果您只想要一项的计数,请使用count 方法:

    >>> [1, 2, 3, 4, 1, 4, 1].count(1)
    3
    

    关于计数性能的重要说明

    如果您想计算多个项目,请不要使用它

    在循环中调用 count 需要为每个 count 调用单独遍历列表,这可能对性能造成灾难性影响。

    如果您想计算所有项目,甚至只是多个项目,请使用Counter,如其他答案中所述。

    【讨论】:

    • mylist = [1,7,7,7,3,9,9,9,7,9,10,0] print sorted(set([i for i in mylist if mylist.count(i)>2]))
    • 在我的例子中计算唯一元素会产生以下时间:114.19 秒,list.count()0.53 秒,numpy.unique(list, return_counts = True) Counter 为 0.17 秒。差异是惊人的。
    【解决方案2】:

    如果您使用的是 Python 2.7 或 3.x 并且想要每个元素的出现次数,请使用 Counter

    >>> from collections import Counter
    >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
    >>> Counter(z)
    Counter({'blue': 3, 'red': 2, 'yellow': 1})
    

    【讨论】:

    • 我发现当大量使用它(谈论数百万个字符串)时,它非常慢,因为它调用了isinstance。因此,如果您确定要处理的数据,最好编写一个不检查类型和实例的自定义函数。
    • @BramVanroy:isinstance 叫什么?即使有数百万个字符串,调用Counter 只涉及一次isinstance 调用,以检查其参数是否为映射。你很可能一直误判你吃的东西。
    • 您误解了我的意思:计数器在创建计数器之前检查您的数据类型。如果您事先知道数据的类型,这需要相对较长的时间。如果你看一下 Counter 的更新方法,你会发现它在做某事之前必须经过三个 if 语句。如果您经常调用更新,这会很快增加。当您可以控制您的数据并且您知道输入确实是可迭代的,那么您可以跳过前两个检查。正如我所说,我只在处理数百万更新时才注意到这一点,所以这是一个边缘案例。
    • @BramVanroy:如果您要执行数百万次更新,而不是仅仅计算数百万个字符串,那就另当别论了。 Counter 中的优化工作已用于计算大型可迭代对象,而不是计算许多可迭代对象。使用Counter 计算一百万个字符串的迭代将比手动实现更快。如果你想用许多迭代调用update,你可以通过使用itertools.chain将它们加入一个迭代来加快速度。
    • 如果你想对结果进行排序how-to-sort-counter-by-value-python --> x = Counter({'a':5, 'b':3, 'c':7}) x.most_common()
    【解决方案3】:

    计算列表中一项的出现次数

    要计算一个列表项的出现次数,您可以使用count()

    >>> l = ["a","b","b"]
    >>> l.count("a")
    1
    >>> l.count("b")
    2
    

    计算列表中所有项的出现次数也称为“计数”列表或创建计数计数器。

    使用 count() 计算所有项目

    要计算 l 中项目的出现次数,可以简单地使用列表推导和 count() 方法

    [[x,l.count(x)] for x in set(l)]
    

    (或类似的字典dict((x,l.count(x)) for x in set(l))

    例子:

    >>> l = ["a","b","b"]
    >>> [[x,l.count(x)] for x in set(l)]
    [['a', 1], ['b', 2]]
    >>> dict((x,l.count(x)) for x in set(l))
    {'a': 1, 'b': 2}
    

    使用 Counter() 计算所有项目

    或者,Counter 库中的更快的 Counter

    Counter(l)
    

    例子:

    >>> l = ["a","b","b"]
    >>> from collections import Counter
    >>> Counter(l)
    Counter({'b': 2, 'a': 1})
    

    Counter 的速度有多快?

    我检查了Counter 用于统计列表的速度有多快。我用n 的几个值尝试了这两种方法,看起来Counter 的速度快了大约2 倍。

    这是我使用的脚本:

    from __future__ import print_function
    import timeit
    
    t1=timeit.Timer('Counter(l)', \
                    'import random;import string;from collections import Counter;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
                    )
    
    t2=timeit.Timer('[[x,l.count(x)] for x in set(l)]',
                    'import random;import string;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
                    )
    
    print("Counter(): ", t1.repeat(repeat=3,number=10000))
    print("count():   ", t2.repeat(repeat=3,number=10000)
    

    还有输出:

    Counter():  [0.46062711701961234, 0.4022796869976446, 0.3974247490405105]
    count():    [7.779430688009597, 7.962715800967999, 8.420845870045014]
    

    【讨论】:

    • Counter 对于更大的列表方式更快。列表推导方法是 O(n^2),Counter 应该是 O(n)。
    • Counter 的速度不是原来的 2 倍,而是 Counter 的速度是 n 倍(O(n^2) vs O(n))。
    • 我发现当大量使用它(谈论数百万个字符串)时,它非常慢,因为它调用了isinstance。因此,如果您确定要处理的数据,最好编写一个不检查类型和实例的自定义函数。
    【解决方案4】:

    在字典中获取每个项目出现次数的另一种方法:

    dict((i, a.count(i)) for i in a)
    

    【讨论】:

    • 这看起来像是我在激烈的战斗中经常想出的结构之一,但它会运行 len(a) 次,这意味着二次运行时复杂度(因为每次运行都取决于 len (a) 再次)。
    • dict((i,a.count(i)) for i in set(a)) 会更正确更快吗?
    • @hugo24:有点,但在最坏的情况下不会渐近更快;它将花费n * (number of different items) 操作,不计算构建集合所需的时间。使用collections.Counter 确实好多了。
    • 派对很晚,但如果列表包含多个i 实例,则不会跟随代码抛出错误,因为它会尝试在字典中输入多个具有相同值的键。 dict((i, a.count(i)) for i in a)
    • @rp1 你可以自己试试看,后面的键值对只是覆盖了同一个键的前一个条目,例如dict([(1, 2), (1, 3)])返回{1: 3}
    【解决方案5】:

    给定一个项目,如何计算它在 Python 列表中出现的次数?

    这是一个示例列表:

    >>> l = list('aaaaabbbbcccdde')
    >>> l
    ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
    

    list.count

    list.count 方法

    >>> l.count('b')
    4
    

    这适用于任何列表。元组也有这种方法:

    >>> t = tuple('aabbbffffff')
    >>> t
    ('a', 'a', 'b', 'b', 'b', 'f', 'f', 'f', 'f', 'f', 'f')
    >>> t.count('f')
    6
    

    collections.Counter

    然后是 collections.Counter。您可以将任何可迭代对象转储到 Counter 中,而不仅仅是列表,并且 Counter 将保留元素计数的数据结构。

    用法:

    >>> from collections import Counter
    >>> c = Counter(l)
    >>> c['b']
    4
    

    计数器基于 Python 字典,它们的键是元素,因此键需要是可散列的。它们基本上就像允许冗余元素进入其中的集合。

    collections.Counter的进一步使用

    您可以使用计数器中的可迭代对象进行加减:

    >>> c.update(list('bbb'))
    >>> c['b']
    7
    >>> c.subtract(list('bbb'))
    >>> c['b']
    4
    

    您还可以使用计数器进行多组操作:

    >>> c2 = Counter(list('aabbxyz'))
    >>> c - c2                   # set difference
    Counter({'a': 3, 'c': 3, 'b': 2, 'd': 2, 'e': 1})
    >>> c + c2                   # addition of all elements
    Counter({'a': 7, 'b': 6, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
    >>> c | c2                   # set union
    Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
    >>> c & c2                   # set intersection
    Counter({'a': 2, 'b': 2})
    

    为什么不用熊猫?

    另一个答案建议:

    为什么不使用熊猫?

    Pandas 是一个通用库,但它不在标准库中。将其添加为要求并非易事。

    在列表对象本身以及标准库中都有针对此用例的内置解决方案。

    如果您的项目还没有需要 pandas,那么仅将其作为此功能的要求将是愚蠢的。

    【讨论】:

    • 虽然“为什么不使用 Pandas”是合适的,但它可能应该伴随着“何时使用 NumPy”,即对于大型数字数组。决定因素不仅仅是项目限制,还有 NumPy 的内存效率,这在大数据中变得显而易见。
    • 感谢您提到 Pandas/etc 是一个严重的依赖项。其中一些软件包具有负面影响。因此,为琐碎的需求添加这些资产可能会花费大量时间和美元。就我个人而言,我体验过 Numpy 和 SciPi 将 30 分钟添加到我们的 CI 管道中,并且需要数天才能正确获取包缓存。很棒的套餐,但有时会有隐藏的费用。 +1 了
    【解决方案6】:

    list.count(x) 返回x 在列表中出现的次数

    见: http://docs.python.org/tutorial/datastructures.html#more-on-lists

    【讨论】:

      【解决方案7】:

      我已经将所有建议的解决方案(以及一些新的解决方案)与perfplot(我的一个小项目)进行了比较。

      计数一个

      对于足够大的数组,事实证明

      numpy.sum(numpy.array(a) == 1)
      

      比其他解决方案稍快。

      统计所有

      As established before,

      numpy.bincount(a)
      

      是你想要的。


      重现情节的代码:

      from collections import Counter
      from collections import defaultdict
      import numpy
      import operator
      import pandas
      import perfplot
      
      
      def counter(a):
          return Counter(a)
      
      
      def count(a):
          return dict((i, a.count(i)) for i in set(a))
      
      
      def bincount(a):
          return numpy.bincount(a)
      
      
      def pandas_value_counts(a):
          return pandas.Series(a).value_counts()
      
      
      def occur_dict(a):
          d = {}
          for i in a:
              if i in d:
                  d[i] = d[i]+1
              else:
                  d[i] = 1
          return d
      
      
      def count_unsorted_list_items(items):
          counts = defaultdict(int)
          for item in items:
              counts[item] += 1
          return dict(counts)
      
      
      def operator_countof(a):
          return dict((i, operator.countOf(a, i)) for i in set(a))
      
      
      perfplot.show(
          setup=lambda n: list(numpy.random.randint(0, 100, n)),
          n_range=[2**k for k in range(20)],
          kernels=[
              counter, count, bincount, pandas_value_counts, occur_dict,
              count_unsorted_list_items, operator_countof
              ],
          equality_check=None,
          logx=True,
          logy=True,
          )
      
      from collections import Counter
      from collections import defaultdict
      import numpy
      import operator
      import pandas
      import perfplot
      
      
      def counter(a):
          return Counter(a)
      
      
      def count(a):
          return dict((i, a.count(i)) for i in set(a))
      
      
      def bincount(a):
          return numpy.bincount(a)
      
      
      def pandas_value_counts(a):
          return pandas.Series(a).value_counts()
      
      
      def occur_dict(a):
          d = {}
          for i in a:
              if i in d:
                  d[i] = d[i] + 1
              else:
                  d[i] = 1
          return d
      
      
      def count_unsorted_list_items(items):
          counts = defaultdict(int)
          for item in items:
              counts[item] += 1
          return dict(counts)
      
      
      def operator_countof(a):
          return dict((i, operator.countOf(a, i)) for i in set(a))
      
      
      b = perfplot.bench(
          setup=lambda n: list(numpy.random.randint(0, 100, n)),
          n_range=[2 ** k for k in range(20)],
          kernels=[
              counter,
              count,
              bincount,
              pandas_value_counts,
              occur_dict,
              count_unsorted_list_items,
              operator_countof,
          ],
          equality_check=None,
      )
      b.save("out.png")
      b.show()
      

      【讨论】:

      • numpy.bincount() 仅适用于具有 int 项目的列表。
      • 第一个程序实际上并没有测量计数一个项目,是吗?看起来它和第二个程序一样。你能检查/修复它吗?我认为numpy.random.randint(0, 100, n).tolist() 会更好。使用您的list(numpy.random.randint(0, 100, n)),您在 Python 列表中有 NumPy 整数,这看起来很奇怪/不切实际。
      【解决方案8】:

      如果您想一次计算所有值,您可以使用 numpy 数组和bincount 快速完成,如下所示

      import numpy as np
      a = np.array([1, 2, 3, 4, 1, 4, 1])
      np.bincount(a)
      

      给了

      >>> array([0, 3, 1, 1, 2])
      

      【讨论】:

        【解决方案9】:

        如果你可以使用pandas,那么value_counts 可以用来救援。

        >>> import pandas as pd
        >>> a = [1, 2, 3, 4, 1, 4, 1]
        >>> pd.Series(a).value_counts()
        1    3
        4    2
        3    1
        2    1
        dtype: int64
        

        它也会根据频率自动对结果进行排序。

        如果您希望结果在列表列表中,请执行以下操作

        >>> pd.Series(a).value_counts().reset_index().values.tolist()
        [[1, 3], [4, 2], [3, 1], [2, 1]]
        

        【讨论】:

        【解决方案10】:

        为什么不使用 Pandas?

        import pandas as pd
        
        my_list = ['a', 'b', 'c', 'd', 'a', 'd', 'a']
        
        # converting the list to a Series and counting the values
        my_count = pd.Series(my_list).value_counts()
        my_count
        

        输出:

        a    3
        d    2
        b    1
        c    1
        dtype: int64
        

        如果您要查找特定元素的计数,例如 a,请尝试:

        my_count['a']
        

        输出:

        3
        

        【讨论】:

          【解决方案11】:

          我今天遇到了这个问题,并在我想检查 SO 之前推出了自己的解决方案。这个:

          dict((i,a.count(i)) for i in a)
          

          对于大型列表来说真的非常慢。我的解决方案

          def occurDict(items):
              d = {}
              for i in items:
                  if i in d:
                      d[i] = d[i]+1
                  else:
                      d[i] = 1
          return d
          

          实际上比 Counter 解决方案快一点,至少对于 Python 2.7 而言。

          【讨论】:

          • 计数器对条目进行排序,而您的不是,因此速度差异(在撰写本文时为真,不确定是否是在您写答案时。不过,它可能与向下滚动的人相关.)
          • Python 2 中的计数器有点慢,是的。然而,它使用 C 优化代码在 Python 3 中进行计数,现在可以轻松击败您的循环。
          【解决方案12】:
          # Python >= 2.6 (defaultdict) && < 2.7 (Counter, OrderedDict)
          from collections import defaultdict
          def count_unsorted_list_items(items):
              """
              :param items: iterable of hashable items to count
              :type items: iterable
          
              :returns: dict of counts like Py2.7 Counter
              :rtype: dict
              """
              counts = defaultdict(int)
              for item in items:
                  counts[item] += 1
              return dict(counts)
          
          
          # Python >= 2.2 (generators)
          def count_sorted_list_items(items):
              """
              :param items: sorted iterable of items to count
              :type items: sorted iterable
          
              :returns: generator of (item, count) tuples
              :rtype: generator
              """
              if not items:
                  return
              elif len(items) == 1:
                  yield (items[0], 1)
                  return
              prev_item = items[0]
              count = 1
              for item in items[1:]:
                  if prev_item == item:
                      count += 1
                  else:
                      yield (prev_item, count)
                      count = 1
                      prev_item = item
              yield (item, count)
              return
          
          
          import unittest
          class TestListCounters(unittest.TestCase):
              def test_count_unsorted_list_items(self):
                  D = (
                      ([], []),
                      ([2], [(2,1)]),
                      ([2,2], [(2,2)]),
                      ([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
                      )
                  for inp, exp_outp in D:
                      counts = count_unsorted_list_items(inp) 
                      print inp, exp_outp, counts
                      self.assertEqual(counts, dict( exp_outp ))
          
                  inp, exp_outp = UNSORTED_WIN = ([2,2,4,2], [(2,3), (4,1)])
                  self.assertEqual(dict( exp_outp ), count_unsorted_list_items(inp) )
          
          
              def test_count_sorted_list_items(self):
                  D = (
                      ([], []),
                      ([2], [(2,1)]),
                      ([2,2], [(2,2)]),
                      ([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
                      )
                  for inp, exp_outp in D:
                      counts = list( count_sorted_list_items(inp) )
                      print inp, exp_outp, counts
                      self.assertEqual(counts, exp_outp)
          
                  inp, exp_outp = UNSORTED_FAIL = ([2,2,4,2], [(2,3), (4,1)])
                  self.assertEqual(exp_outp, list( count_sorted_list_items(inp) ))
                  # ... [(2,2), (4,1), (2,1)]
          

          【讨论】:

          • @plaes:怎么会这样?如果“企业”是指为准备 Py3k 注释而“记录”,我同意。
          • 这是一个很好的例子,因为我主要在 2.7 中开发,但必须有到 2.4 的迁移路径。
          【解决方案13】:

          以下是三种解决方案:

          最快的是使用 for 循环并将其存储在字典中。

          import time
          from collections import Counter
          
          
          def countElement(a):
              g = {}
              for i in a:
                  if i in g: 
                      g[i] +=1
                  else: 
                      g[i] =1
              return g
          
          
          z = [1,1,1,1,2,2,2,2,3,3,4,5,5,234,23,3,12,3,123,12,31,23,13,2,4,23,42,42,34,234,23,42,34,23,423,42,34,23,423,4,234,23,42,34,23,4,23,423,4,23,4]
          
          
          #Solution 1 - Faster
          st = time.monotonic()
          for i in range(1000000):
              b = countElement(z)
          et = time.monotonic()
          print(b)
          print('Simple for loop and storing it in dict - Duration: {}'.format(et - st))
          
          #Solution 2 - Fast
          st = time.monotonic()
          for i in range(1000000):
              a = Counter(z)
          et = time.monotonic()
          print (a)
          print('Using collections.Counter - Duration: {}'.format(et - st))
          
          #Solution 3 - Slow
          st = time.monotonic()
          for i in range(1000000):
              g = dict([(i, z.count(i)) for i in set(z)])
          et = time.monotonic()
          print(g)
          print('Using list comprehension - Duration: {}'.format(et - st))
          

          结果

          #Solution 1 - Faster
          
          {1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 234: 3, 23: 10, 12: 2, 123: 1, 31: 1, 13: 1, 42: 5, 34: 4, 423: 3}
          Simple for loop and storing it in dict - Duration: 12.032000000000153
          
          #Solution 2 - Fast
          
          Counter({23: 10, 4: 6, 2: 5, 42: 5, 1: 4, 3: 4, 34: 4, 234: 3, 423: 3, 5: 2, 12: 2, 123: 1, 31: 1, 13: 1})
          Using collections.Counter - Duration: 15.889999999999418
          
          #Solution 3 - Slow
          
          {1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 34: 4, 423: 3, 234: 3, 42: 5, 12: 2, 13: 1, 23: 10, 123: 1, 31: 1}
          Using list comprehension - Duration: 33.0
          

          【讨论】:

          • 如@user52028778 上面的解决方案中提到的那样使用计数器
          • @KishanK 如果您看到我的回答,我也尝试过使用 Counter(Solution 2),但使用循环的 Solution1 仍然比它运行得更快。
          • @AkashSwain 在您实施的方法中,我想您可以通过从列表中删除已经计数的元素来使其运行得更快一些,因为 for 循环不必检查这些...我会复制列表,然后从复制的列表中删除并执行 for 循环,我想您也必须以相反的顺序执行循环,因为您将从列表中删除内容...
          【解决方案14】:

          itertools.groupby() 的所有元素的计数

          获取列表中所有元素的计数的另一种可能性是通过itertools.groupby()

          具有“重复”计数

          from itertools import groupby
          
          L = ['a', 'a', 'a', 't', 'q', 'a', 'd', 'a', 'd', 'c']  # Input list
          
          counts = [(i, len(list(c))) for i,c in groupby(L)]      # Create value-count pairs as list of tuples 
          print(counts)
          

          返回

          [('a', 3), ('t', 1), ('q', 1), ('a', 1), ('d', 1), ('a', 1), ('d', 1), ('c', 1)]
          

          注意它将前三个a 组合为第一组,而a 的其他组在列表的下方。发生这种情况是因为输入列表 L 未排序。如果这些组实际上应该是分开的,这有时会带来好处。

          具有唯一性计数

          如果需要唯一组计数,只需对输入列表进行排序:

          counts = [(i, len(list(c))) for i,c in groupby(sorted(L))]
          print(counts)
          

          返回

          [('a', 5), ('c', 1), ('d', 2), ('q', 1), ('t', 1)]
          

          注意:对于创建唯一计数,与groupby 解决方案相比,许多其他答案提供了更简单、更易读的代码。但这里显示的是与重复计数示例平行。

          【讨论】:

            【解决方案15】:

            虽然这是一个很老的问题,但因为我没有找到一个班轮,所以我做了一个。

            # original numbers in list
            l = [1, 2, 2, 3, 3, 3, 4]
            
            # empty dictionary to hold pair of number and its count
            d = {}
            
            # loop through all elements and store count
            [ d.update( {i:d.get(i, 0)+1} ) for i in l ]
            
            print(d)
            # {1: 1, 2: 2, 3: 3, 4: 1}
            

            【讨论】:

            【解决方案16】:

            建议使用 numpy 的 bincount,但它仅适用于具有 非负整数的一维数组。此外,生成的数组可能会令人困惑(它包含原始列表中从 min 到 max 的整数的出现次数,并将缺失的整数设置为 0)。

            使用 numpy 执行此操作的更好方法是使用 unique 函数并将属性 return_counts 设置为 True。它返回一个包含唯一值数组和每个唯一值出现次数的数组的元组。

            # a = [1, 1, 0, 2, 1, 0, 3, 3]
            a_uniq, counts = np.unique(a, return_counts=True)  # array([0, 1, 2, 3]), array([2, 3, 1, 2]
            

            然后我们可以将它们配对

            dict(zip(a_uniq, counts))  # {0: 2, 1: 3, 2: 1, 3: 2}
            

            它也适用于其他数据类型和“二维列表”,例如

            >>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']]
            >>> dict(zip(*np.unique(a, return_counts=True)))
            {'a': 3, 'b': 3, 'c': 2}
            

            【讨论】:

              【解决方案17】:

              计算具有共同类型的不同元素的数量:

              li = ['A0','c5','A8','A2','A5','c2','A3','A9']
              
              print sum(1 for el in li if el[0]=='A' and el[1] in '01234')
              

              给予

              3,不是 6

              【讨论】:

                【解决方案18】:

                您也可以使用内置模块operatorcountOf方法。

                >>> import operator
                >>> operator.countOf([1, 2, 3, 4, 1, 4, 1], 1)
                3
                

                【讨论】:

                • countOf是如何实现的?它与更明显的list.count(受益于 C 实现)相比如何?有什么优势吗?
                【解决方案19】:

                我会使用filter(),以 Lukasz 为例:

                >>> lst = [1, 2, 3, 4, 1, 4, 1]
                >>> len(filter(lambda x: x==1, lst))
                3
                

                【讨论】:

                • 这会在 python 3.5 中引发异常“对象过滤器没有 len()”
                • 在 Python 3 中,您必须使用 list() 将过滤器对象转换为列表。
                【解决方案20】:

                使用 %timeit 查看哪个操作更有效。 np.array 计数操作应该更快。

                 from collections import Counter
                 mylist = [1,7,7,7,3,9,9,9,7,9,10,0] 
                 types_counts=Counter(mylist)
                 print(types_counts)
                

                【讨论】:

                  【解决方案21】:

                  可能不是最有效的,需要额外通过才能删除重复项。

                  功能实现:

                  arr = np.array(['a','a','b','b','b','c'])
                  print(set(map(lambda x  : (x , list(arr).count(x)) , arr)))
                  

                  返回:

                  {('c', 1), ('b', 3), ('a', 2)}
                  

                  或返回dict

                  print(dict(map(lambda x  : (x , list(arr).count(x)) , arr)))
                  

                  返回:

                  {'b': 3, 'c': 1, 'a': 2}
                  

                  【讨论】:

                    【解决方案22】:

                    给定一个列表 X

                     import numpy as np
                     X = [1, -1, 1, -1, 1]
                    

                    显示此列表元素的 i: frequency(i) 的字典是:

                    {i:X.count(i) for i in np.unique(X)}
                    

                    输出:

                    {-1: 2, 1: 3}
                    

                    【讨论】:

                    • 在创建列表时,numpy 是否以智能方式预先计算?如果不是,这是一个 O(n^2)。
                    【解决方案23】:
                    sum([1 for elem in <yourlist> if elem==<your_value>])
                    

                    这将返回 your_value 的出现次数

                    【讨论】:

                      【解决方案24】:

                      或者,您也可以自己实现计数器。我就是这样做的:

                      item_list = ['me', 'me', 'you', 'you', 'you', 'they']
                      
                      occ_dict = {}
                      
                      for item in item_list:
                          if item not in occ_dict:
                              occ_dict[item] = 1
                          else:
                              occ_dict[item] +=1
                      
                      print(occ_dict)
                      

                      输出:{'me': 2, 'you': 3, 'they': 1}

                      【讨论】:

                        【解决方案25】:
                        mot = ["compte", "france", "zied"]
                        lst = ["compte", "france", "france", "france", "france"]
                        dict((x, lst.count(x)) for x in set(mot))
                        

                        这给了

                        {'compte': 1, 'france': 4, 'zied': 0}
                        

                        【讨论】:

                          【解决方案26】:

                          如果您希望特定元素出现多次:

                          >>> from collections import Counter
                          >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
                          >>> single_occurrences = Counter(z)
                          >>> print(single_occurrences.get("blue"))
                          3
                          >>> print(single_occurrences.values())
                          dict_values([3, 2, 1])
                          

                          【讨论】:

                            【解决方案27】:
                            l2=[1,"feto",["feto",1,["feto"]],['feto',[1,2,3,['feto']]]]
                            count=0
                             def Test(l):   
                                    global count 
                                    if len(l)==0:
                                         return count
                                    count=l.count("feto")
                                    for i in l:
                                         if type(i) is list:
                                            count+=Test(i)
                                    return count   
                                print(Test(l2))
                            

                            这将递归计数或搜索列表中的项目,即使它在列表列表中

                            【讨论】:

                            • 我不知道为什么有人只是对答案投了反对票,而且它完全有用
                            【解决方案28】:
                            test = [409.1, 479.0, 340.0, 282.4, 406.0, 300.0, 374.0, 253.3, 195.1, 269.0, 329.3, 250.7, 250.7, 345.3, 379.3, 275.0, 215.2, 300.0]
                            
                            for i in test:
                                print('{} numbers {}'.format(i, test.count(i)))
                            

                            【讨论】:

                              【解决方案29】:
                              def countfrequncyinarray(arr1):
                                  r=len(arr1)
                                  return {i:arr1.count(i) for i in range(1,r+1)}
                              arr1=[4,4,4,4]
                              a=countfrequncyinarray(arr1)
                              print(a)
                              

                              【讨论】:

                              • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
                              猜你喜欢
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 2021-07-29
                              • 2012-07-12
                              相关资源
                              最近更新 更多