Home >Backend Development >Python Tutorial >How to use the Counter module in Python

How to use the Counter module in Python

PHPz
PHPzforward
2023-04-19 14:55:082720browse

Description

Project Description
Python Interpreter 3.10. 6

Counter module

In Python’s collections module, a very commonly used module is Counter. Counter is a simple counter used to count the number of certain hashable objects. It stores elements and their counts in the form of a dictionary.

Counter() class

ClassCounter() can count the parameters passed to this class according to certain rules, and use the counting object and the counting result as the key The value pairs are returned in the form of a dictionary.

Counter(iterable=None, /, **kwds)

Give a chestnut

from collections import Counter
# 返回一个空的 Counter 对象
cnt = Counter()
print(cnt)

# 将可迭代对象(字符串)作为参数
cnt = Counter('Hello World')
print(cnt)

# 将可迭代对象(列表)作为参数
cnt = Counter(['a', 'a', 'b', 'd', 'c', 'd'])
print(cnt)

# 使用可迭代对象(字典)作为参数
cnt = Counter({'a': 1, 'b': 2, 'd': 3, 'c': 2})
print(cnt)

# 使用关键字参数
cnt = Counter(a=1, b=2, d=3, c=2)
print(cnt)

Execution effect

Counter()
Counter({' l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1})
Counter({'a': 2, 'd': 2, 'b': 1, 'c': 1})
Counter({'d': 3, 'b': 2, 'c': 2, 'a': 1})
Counter({'d': 3, 'b': 2, 'c': 2, 'a': 1})

Counter () Object

Dictionary

The result returned by Counter() is a dictionary, which has most of the methods of an ordinary dictionary. In most cases, you can operate Counter objects just like dictionaries. For this, please refer to the following example:

from collections import Counter
cnt = Counter('Hello World')
print(cnt)

# 输出 Counter 对象中的键值对列表
print(cnt.items())

# 移除 Counter 对象中的最后一个键值对
print(cnt.popitem())
print(cnt)

# 输出 Counter 中键 l 对应的值
print(cnt['l'])

Execution result

Counter({'l': 3, 'o': 2, 'H' : 1, 'e': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1})
dict_items([('H', 1), ('e ', 1), ('l', 3), ('o', 2), (' ', 1), ('W', 1), ('r', 1), ('d', 1 )])
('d', 1)
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'W ': 1, 'r': 1})
3

Ordering

Dictionaries in Python are unordered,Unordered## The meaning of # does not mean that the key-value pairs in the dictionary have no order, but that the order of the key-value pairs in the dictionary is unpredictable. For this, please refer to the following example:

d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
    print(key)

The output of this example may be:

a

b
c

It may also be :

b

c
a

Of course there are other possibilities, so I won’t list them all here.

Python has officially optimized the dictionary in the

Python 3.6 version so that it can remember the order in which key-value pairs are inserted. After this, the dictionary looks less cluttered (the order of key-value pairs in the dictionary becomes predictable).

KeyError

In Python's built-in dictionary, if you try to access a key that does not exist, Python will throw a

KeyError exception error. For this, please refer to the following example:

d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d)

# 尝试访问字典 d 中不存在的键
print(d['d'])

Execution effect

Traceback (most recent call last):

File "C:\main. py", line 5, in 4225fa317875f3e92281a7b1a5733569
print(d['d'])
KeyError: 'd'
{'a': 1, 'b': 2, 'c' : 3}

Same scene. This time, we have Counter as the protagonist.

from collections import Counter
cnt = Counter({'a': 1, 'b': 2, 'c': 3})
print(cnt)

# 尝试访问 Counter 中不存在的键
print(cnt['d'])

Execution effect

When accessing a key that does not exist in the Counter object, the

KeyError exception will not be thrown, but Returns the default count value 0.

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

0

Magic method__missing__

__missing__() is a special method in Python used to handle the situation when the key does not exist when accessing the value in the dictionary by key. When we use a dictionary index to access a key that does not exist, Python will call the special method
__missing__() to try to return a suitable value. If the __missing__() method is not implemented, Python will throw a KeyError exception. For this, please refer to the following example:

# 创建一个字典对象,该对象继承自 Python 内置的 dict 对象
class MyDict(dict):
    def __missing__(self, key):
        return 0

# 实例化 MyDict() 对象
myDict = MyDict()
# 尝试访问 myDict 对象中不存在的键 a
print(myDict['a'])

Execution effect

0

update() method

# The

##Counter

object and the dict object also implement the update() method. Use the update() method to merge the dictionary as a parameter into the dict object that calls the method. The difference is that when the update() method of the dict object encounters the same key, it will perform the overwrite operation on the value corresponding to the key. When the update() method of the Counter object encounters the same key, it will perform the overlay operation on the value corresponding to the key. For this, please refer to the following example:

from collections import Counter
# Python 中内置的 dict 对象
d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d)

d.update({'a': 4})
print(d)

print()

# Counter 对象
cnt = Counter({'a': 1, 'b': 2, 'c': 3})
print(cnt)

cnt.update({'a': 4})
print(cnt)

Execution effect

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


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

Counter({'a': 5, 'c': 3, 'b': 2})

Counter 对象的常用方法

most_common()

most_common() 方法将返回一个列表,列表中的元素均为 Counter 对象中的键值对组成的元组。元组在列表中的顺序取决于计数值(键值对中的值)的大小。计数值更大的元组将位于列表的前端,计数值相等的元组将按照它们首次在列表中出现的顺序进行排列(先出现的元组将更靠近列表的前端)。
most_common() 默认将使用 Counter 对象中所有的键值对组成的元组作为返回列表中的元素。你可以通过向该方法提供一个数值,该数值将指定放回的列表中的元素的数量。

举个栗子

from collections import Counter
cnt = Counter({'a': 1, 'b': 2, 'c': 3})
print(cnt)

print()

print(cnt.most_common())
# 返回由 Counter 中计数值最大的两个
# 键值对构成的元组所组成的列表
print(cnt.most_common(2))
# 返回由 Counter 中计数值最大的
# 键值对构成的元组所组成的列表
print(cnt.most_common(1))

执行效果

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

[('c', 3), ('b', 2), ('a', 1)]
[('c', 3), ('b', 2)]
[('c', 3)]

elements()

elements() 方法将返回一个以 Counter 对象中的键为元素的迭代器,其中每个元素将重复出现计数值所指定的次数。

迭代器中的元素将存在如下特点:

  • 元素将会按照其首次添加到 Counter 对象中的顺序进行返回。

  • 某个键对应的计数值小于一,那么该键将不会作为元素出现在 element() 方法返回的迭代器中。

举个栗子

from collections import Counter
cnt = Counter({'a': 1, 'b': 2, 'c': 3, 'd': -4})
print(cnt)

print()

print(list(cnt.elements()))

执行效果

Counter({'c': 3, 'b': 2, 'a': 1, 'd': -4})

['a', 'b', 'b', 'c', 'c', 'c']

total()

total() 方法将返回 Counter 对象中,所有计数值累加后得到的结果。对此,请参考如下示例:

from collections import Counter
cnt = Counter({'a': 1, 'b': 2, 'c': 3, 'd': -4})
cnt1 = Counter('Hello World')
print(cnt.total())
print(cnt1.total())

执行效果

2
11

subtract()

该方法的效果与 Counter 对象的 update() 方法类似。如果说 update() 方法执行的是 操作,那么 subtract() 方法执行的则是 操作。对此,请参考如下示例:

from collections import Counter
cnt = Counter({'a': 1, 'b': 2, 'c': 3, 'd': -4})

cnt.subtract({'a': 0, 'b': 1, 'd': -11})
print(cnt)

执行效果

Counter({'d': 7, 'c': 3, 'a': 1, 'b': 1})

Counter 对象间的运算

注:

本部分内容中讲解到的运算符仅能在 Python 3.3 及以后版本中正常使用。

加法运算

在 Python 的 Counter 模块中,两个 Counter 对象可以相加,相加后将返回一个新的 Counter 对象,其中每个元素的计数是两个原始 Counter 对象中该元素计数的总和。可以通过使用加法运算符来执行此操作。对此,请参考如下示例:

from collections import Counter

cnt = Counter('Hello')
cnt1 = Counter('World')

print(cnt)
print(cnt1)
print(cnt + cnt1)

执行效果

Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
Counter({'W': 1, 'o': 1, 'r': 1, 'l': 1, 'd': 1})
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, 'W': 1, 'r': 1, 'd': 1})

注:

在 Counter 对象间的运算过程中,对于 Counter 中不存在的键,其计数值为零。

减法运算

在 Python 的 Counter 模块中,可以使用减法运算符来对两个 Counter 对象进行减法运算,即将左侧 Counter 对象中的计数器值减去右侧 Counter 对象中相同键的计数器值,最后返回一个新的 Counter 对象。对此,请参考如下示例:

from collections import Counter

cnt = Counter('cook')
cnt1 = Counter('coder')

print(cnt)
print(cnt1)
print(cnt - cnt1)

执行效果

Counter({'o': 2, 'c': 1, 'k': 1})
Counter({'c': 1, 'o': 1, 'd': 1, 'e': 1, 'r': 1})
Counter({'o': 1, 'k': 1})

注:

在 Counter 对象间的运算过程中,对于 Counter 中不存在的键,其计数值为零。

并集运算

Counter 对象之间的并集运算是指两个 Counter 对象按照键的并集进行运算,返回的结果是一个新的 Counter 对象,其中包含的键和值均为 原始 Counter 对象中存在的键及其对应的最大值。对此,请参考如下示例:

from collections import Counter

cnt = Counter('Hello')
cnt1 = Counter('World')

print(cnt)
print(cnt1)
print(cnt | cnt1)

执行效果

Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
Counter({'W': 1, 'o': 1, 'r': 1, 'l': 1, 'd': 1})
Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1, 'W': 1, 'r': 1, 'd': 1})

交集运算

Counter 对象之间的交集运算是指两个 Counter 对象按照键的交集进行运算,返回的结果是一个新的 Counter 对象,其中包含的键和值均为 原始 Counter 对象中共同拥有的键及其对应的最小值。对此,请参考如下示例:

from collections import Counter

cnt = Counter('Hello')
cnt1 = Counter('World')

print(cnt)
print(cnt1)
print(cnt & cnt1)

执行效果

Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
Counter({'W': 1, 'o': 1, 'r': 1, 'l': 1, 'd': 1})
Counter({'l': 1, 'o': 1})

单目运算

单目运算指的是表达式中存在单目运算符的运算操作。存在两种单目运算符,即单目减法运算符与单目加法运算符。无论是单目减法运算符还是单目加法运算符,它们的操作对象均为 Counter 对象中的计数值。
在对 Counter 对象进行单目运算后,将返回一个由大于零的计数值相关的键值对组成的 Counter 对象。对此,请参考如下示例:

from collections import Counter

cnt = Counter({'a': 4, 'b': 3, 'd': 0, 'c': -5})
print(+cnt)
print(-cnt)

执行效果

Counter({'a': 4, 'b': 3})
Counter({'c': 5})

Counter 对象间的比较

Python 3.10 版本开始,Counter 对象间开始支持常见的比较运算符,这些运算符有:

  • f9650ea21636727e735f43a99741058c

  • >=

  • ==

  • !=

这里以 >== 为例进行讲解。

>

> 的左侧的 Counter 对象的键对应的计数值均大于该符号右侧的 Counter 对象中相同的键(对于 Counter 中不存在的键,其计数值为零)对应的计数值时,比较结果为 True。否则为 False。对此,请参考如下示例:

from collections import Counter

cnt = Counter({'a': 4, 'b': 3, 'd': 7, 'c': 5})
cnt1 = Counter({'c': 3, 'd': 2, 'b': 6, 'a': 4})
cnt2 = Counter({'c': 4, 'd': 6, 'b': 2, 'a': 3})

print(cnt > cnt1)
print(cnt > cnt2)

执行效果

False
True

==

== 的左侧的 Counter 对象的键对应的计数值均等于该符号右侧的 Counter 对象中相同的键(对于 Counter 中不存在的键,其计数值为零)对应的计数值时,比较结果为 True。否则为 False。对此,请参考如下示例:

from collections import Counter

cnt = Counter({'a': 3, 'b': 2, 'd': 6, 'c': 4})
cnt1 = Counter({'c': 3, 'd': 2, 'b': 6, 'a': 4})
cnt2 = Counter({'c': 4, 'd': 6, 'b': 2, 'a': 3})

print(cnt == cnt1)
print(cnt == cnt2)

执行效果

False
True

The above is the detailed content of How to use the Counter module in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete