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


一个相关但不同的问题是计算集合中每个不同元素的出现次数,将字典或列表作为直方图结果而不是单个整数。有关该问题,请参阅使用字典统计列表中的项目。


当前回答

我今天遇到了这个问题,在我想检查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来说是这样。

其他回答

x = ['Jess', 'Jack', 'Mary', 'Sophia', 'Karen',
     'Addison', 'Joseph','Jack', 'Jack', 'Eric', 'Ilona', 'Jason']
the_item = input('Enter the item that you wish to find : ')
how_many_times = 0 
for occurrence in x:
     if occurrence == the_item : 
          how_many_times += 1
print('The occurrence of', the_item, 'in', x,'is',how_many_times) 

创建了一个名字列表,其中重复了“Jack”这个名字。为了检查它的发生情况,我在名为x的列表中运行了一个for循环。每次迭代时,如果循环变量的值与从用户接收的值相同,并存储在变量the_item中,那么变量how_many_times将递增1。在获得某种价值之后。。。我们打印how_many_times,它存储单词“jack”出现的值

使用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解决方案相比,许多其他答案提供了更简单、更可读的代码。但这里显示的是与重复计数示例平行。

要计算具有共同类型的不同元素的数量,请执行以下操作:

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

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

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

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