Collections 模块中的 Python Counter 及示例

什么是 Python Counter?

Python Counter 是一个容器,用于统计容器中每个元素的出现次数。Counter 是字典类中一个子类。

Counter 是字典类中一个子类。使用 Python Counter 工具,您可以统计对象(也称为哈希表对象)中的键值对数量。

为什么使用 Python Counter?

以下是使用 Python 3 Counter 的主要原因:

  • Counter 以无序集合的形式存储数据,就像哈希表对象一样。其中的元素代表键,计数作为值。
  • 它允许您统计可迭代列表中的项。
  • 加法、减法、交集和并集等算术运算可以轻松地在 Counter 上执行。
  • Counter 也可以计算另一个 Counter 中的元素

Python Counter 简介

Python Counter 接受列表、元组、字典、字符串等可迭代对象作为输入,并输出每个元素的计数。

语法

Counter(list)

假设您有一个以下列表

list1 = ['x','y','z','x','x','x','y', 'z']

该列表包含元素 x、y 和 z。当您将 Counter 用于此列表时,它将计算 x、y 和 z 出现的次数。如果对 list1 使用 Counter,输出应如下所示:

Counter({'x': 4, 'y': 2, 'z': 2})

因此,x 的计数为 4,y 的计数为 2,z 的计数为 2。

要使用 Counter,我们首先需要像下面示例一样导入它:

from collections import Counter

这是一个简单的示例,展示了 Counter 模块的工作原理。

from collections import Counter
list1 = ['x','y','z','x','x','x','y', 'z']
print(Counter(list1))

输出

Counter({'x': 4, 'y': 2, 'z': 2})

字符串 Counter

在 Python 中,万物皆对象,字符串也不例外。Python 字符串可以通过将字符括在双引号中来创建。Python 不支持字符类型,它们被视为长度为一的字符串,也被视为子字符串。

在下面的示例中,将一个字符串传递给 Counter。它返回字典格式,包含键/值对,其中键是元素,值是计数。它还将空格视为一个元素并给出字符串中空格的计数。

示例

from collections import Counter
my_str = "Welcome to Guru99 Tutorials!"
print(Counter(my_str))

输出

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1,
 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

列表 Counter

列表是一个可迭代对象,其元素用方括号括起来。

当将列表中的元素提供给 Counter 时,它们将被转换为哈希表对象,其中元素将成为键,值将是所提供列表的元素计数。

例如 [‘x’,’y’,’z’,’x’,’x’,’x’,’y’,’z’]。将列表提供给 Counter 后,它将为您提供列表中每个元素的计数。

from collections import Counter
list1 = ['x','y','z','x','x','x','y','z']
print(Counter(list1))

输出

Counter({'x': 4, 'y': 2, 'z': 2})

字典 Counter

字典包含键/值对元素,并用花括号括起来。

一旦将字典提供给 Counter,它将被转换为哈希表对象,其中元素将成为键,值将是所提供字典的元素计数。

例如:{‘x’: 4, ‘y’: 2, ‘z’: 2, ‘z’: 2}。Counter 函数将尝试查找给定字典中每个键的计数。

from collections import Counter
dict1 =  {'x': 4, 'y': 2, 'z': 2, 'z': 2}
print(Counter(dict1))

输出

Counter({'x': 4, 'y': 2, 'z': 2})

元组 Counter

元组是圆括号内由逗号分隔的对象集合。Counter 将为您提供给定元组中每个元素的计数。

一旦将元组提供给 Counter,它将被转换为哈希表对象,其中元素将成为键,值将是所提供元组的元素计数。

from collections import Counter
tuple1 = ('x','y','z','x','x','x','y','z')
print(Counter(tuple1))

输出

Counter({'x': 4, 'y': 2, 'z': 2})

访问、初始化和更新 Counter

初始化 Counter

可以通过传递字符串值、列表、字典或元组来初始化 Counter,如下所示:

from collections import Counter
print(Counter("Welcome to Guru99 Tutorials!"))   #using string
print(Counter(['x','y','z','x','x','x','y', 'z'])) #using list
print(Counter({'x': 4, 'y': 2, 'z': 2})) #using dictionary
print(Counter(('x','y','z','x','x','x','y', 'z'))) #using tuple

您也可以像下面一样初始化一个空的 Counter:

from collections import Counter
_count = Counter()

更新 Counter

您可以使用 update() 方法向 Counter 添加值。

_count.update('Welcome to Guru99 Tutorials!')

最终代码是:

from collections import Counter
_count = Counter()
_count.update('Welcome to Guru99 Tutorials!')
print(_count)

输出是:

Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1,
 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

访问 Counter

要从 Counter 获取值,您可以这样做:

from collections import Counter

_count = Counter()
_count.update('Welcome to Guru99 Tutorials!')
print('%s : %d' % ('u', _count['u']))
print('\n')
for char in 'Guru':
    print('%s : %d' % (char, _count[char]))

输出

u : 3

G : 1
u : 3
r : 2
u : 3

从 Counter 中删除元素

要从 Counter 中删除元素,您可以使用 del,如下面的示例所示:

示例

from collections import Counter
dict1 =  {'x': 4, 'y': 2, 'z': 2}
del dict1["x"]
print(Counter(dict1))

输出

Counter({'y': 2, 'z': 2})

Python Counter 的算术运算

像加法、减法、交集和并集这样的算术运算可以在 Counter 上进行,如下面的示例所示:

示例

from collections import Counter
counter1 =  Counter({'x': 4, 'y': 2, 'z': -2})

counter2 = Counter({'x1': -12, 'y': 5, 'z':4 })

#Addition
counter3 = counter1 + counter2 # only the values that are positive will be returned.

print(counter3)

#Subtraction
counter4 = counter1 - counter2 # all -ve numbers are excluded.For example z will be z = -2-4=-6, since it is -ve value it is not shown in the output

print(counter4)

#Intersection
counter5 = counter1 & counter2 # it will give all common positive minimum values from counter1 and counter2

print(counter5)

#Union
counter6 = counter1 | counter2 # it will give positive max values from counter1 and counter2

print(counter6)

输出

Counter({'y': 7, 'x': 4, 'z': 2})
Counter({'x1': 12, 'x': 4})
Counter({'y': 2})
Counter({'y': 5, 'x': 4, 'z': 4})

Python Counter 可用方法

Counter 附带一些重要方法,以下是它们的列表:

  • elements():此方法将返回所有计数大于 0 的元素。计数为 0 或 -1 的元素将不会返回。
  • most_common(value):此方法将从 Counter 列表中返回最常见的元素。
  • subtract():此方法用于从另一个 Counter 中扣除元素。
  • update():此方法用于从另一个 Counter 中更新元素。

示例:elements()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 2, 'z': -2, 'x1':0})

_elements = counter1.elements() # will give you all elements with positive value and count>0
for a in _elements:
    print(a)

输出

x
x
x
x
x
y
y

示例:most_common(value)

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

common_element = counter1.most_common(2) # The dictionary will be sorted as per the most common element first followed by next.
print(common_element)

common_element1 = counter1.most_common() # if the value is not given to most_common , it will sort the dictionary and give the most common elements from the start.The last element will be the least common element.
print(common_element1)

输出

 [('y', 12), ('x', 5)]
[('y', 12), ('x', 5), ('x1', 0), ('z', -2)]

示例:subtract()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})

counter1.subtract(counter2)
print(counter1)

输出

Counter({'y': 7, 'x': 3, 'x1': 0, 'z': -2})

示例:update()

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})
counter1.update(counter2)
print(counter1)

输出

Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})

在 Python 中重新分配计数

您可以像下面一样重新分配 Counter 的计数:

假设您有一个字典:{'x': 5, 'y': 12, 'z': -2, 'x1':0}

您可以像下面一样更改元素的计数:

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

counter1['y'] = 20

print(counter1)

输出:执行后,您将看到 y 的计数已从 12 更改为 20。

Counter({'y': 20, 'x': 5, 'x1': 0, 'z': -2})

使用 Counter 获取和设置元素的计数

要使用 Counter 获取元素的计数,您可以这样做:

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
print(counter1['y']) # this will give you the count of element 'y'

输出

12

要设置元素的计数,您可以这样做:

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})

print(counter1['y'])

counter1['y'] = 20
counter1['y1'] = 10

print(counter1)

输出

12
Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2})

摘要

  • Counter 是一个容器,用于统计容器中每个元素的出现次数。
  • Counter 是字典类中一个子类。
  • 使用 Python Counter 工具,您可以统计对象(也称为哈希表对象)中的键值对数量。
  • Counter 以无序集合的形式存储数据,就像哈希表对象一样。其中的元素代表键,计数作为值。
  • 它允许您统计可迭代列表中的项。
  • 加法、减法、交集和并集等算术运算可以轻松地在 Counter 上执行。
  • Counter 也可以计算另一个 Counter 中的元素。
  • Counter 的重要方法包括 elements()、most_common(value)、subtract() 和 update()。
  • Counter 可用于字符串、列表、字典和元组。