Counter 是 dictionary 对象的子类。collections 模块中的 Counter() 函数会接收一个诸如 list 或 tuple 的迭代器,然后返回一个 Counter dictionary。这个 dictionary 的键是该迭代器中的唯一元素,每个键的值是迭代器元素的计数。
首先,我们需要从 collections 包中导入 Counter:
from collections import Counter
如果要创建一个 Counter 对象,我们也要像对待其他对象类一样,先将它分配给一个变量,而传递给 Counter 对象的惟一变量即是迭代器。
list = [1, 2, 3, 3, 2, 1, 1, 1, 2, 2, 3, 1, 2, 1, 1]
counter = Counter(list)
如果我们使用简单的 print 函数(print(counter))把这个 Counter 打印出来,则会得到一些与 dictionary 稍微类似的输出:
Counter({1: 7, 2: 5, 3: 3})
你可以用这些键值访问任何 Counter 项。这与从标准的 Python dictionary 中获取元素的方法完全相同。
lst = [1, 2, 3, 3, 2, 1, 1, 1, 2, 2, 3, 1, 2, 1, 1]
counter = Counter(lst)
print(counter[1])
7
most_common() 函数
目前来说,Counter 对象中最有用的函数是 most_common()。当它应用于一个 Counter 对象时,会返回一个 list,这个 list 包含了前 N 个常见的元素及其计数,它们按照常见度降序排列。
lst = [1, 2, 3, 3, 2, 1, 1, 1, 2, 2, 3, 1, 2, 1, 1]
counter = Counter(lst)
print(counter.most_common(2))
上述代码会打印出以下 tuples 的 list。
[(1, 7), (2, 5)]
每个 tuple 的首个元素是 list 中的唯一项,第二个元素是计数值。对于「获取 list 中前 3 常见的元素及其计数」这样的问题,这会是一种快速且简单的方法。
from collections import Counter计数器_Python_ch_improve的博客-CSDN博客
网友评论