计数器是一个容器,用于跟踪添加等效值的次数。Python计数器类是collections模块的一部分,并且是dictionary的子类。

Python计数器

我们可能将counter视为项目的无序集合,其中项目存储为字典键,而其计数为字典值。

计数器项目计数可以为正,零或负整数。尽管对其键和值没有限制,但通常值应为数字,但我们也可以存储其他对象类型。

初始化中

计数器支持三种形式的初始化。可以使用一系列项目,包含键和计数的字典或使用将字符串名称映射到计数的关键字参数来调用其构造函数。import collections

print (collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']))

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

print(collections.Counter(a=2, b=3, c=1))

三种初始化形式的输出都相同-Counter({'b': 3, 'a': 2, 'c': 1})

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

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

要创建一个空计数器,请传递不带参数的计数器,然后通过update方法填充该计数器。import collections

c = collections.Counter()

print('Initial: ', c)

c.update('abcddcba')

print('Sequence: ', c)

c.update({'a': 1, 'd':5})

print('Dict: ', c)

输出结果Initial: Counter()Sequence: Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2})

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

访问计数

一旦填充了计数器,就可以通过字典API获取其值。import collections

c = collections.Counter('abcddcba')

for letter in 'abcdef':

print('%s : %d' %(letter, c[letter]))

输出结果a : 2

b : 2

c : 2

d : 2

e : 0

f : 0

计数器不会针对未知项目(例如,我们在上面的程序中提到的e和f项目)引发KeyError。如果在输入中未看到值,则其计数为0(就像上面输出中的未知项e和f一样)。

该elements()方法返回一个迭代器,该迭代器生成Counter已知的所有项目。import collections

c = collections.Counter('Python Counters')

c['z'] = 0

print(c)

print(list(c.elements()))

输出结果Counter({'t': 2, 'o': 2, 'n': 2, 'P': 1, 'y': 1, 'h': 1, ' ': 1, 'C': 1, 'u': 1, 'e': 1, 'r': 1, 's': 1, 'z': 0})

['P', 'y', 't', 't', 'h', 'o', 'o', 'n', 'n', ' ', 'C', 'u', 'e', 'r', 's']

元素的顺序不是固定的,不包括计数小于零的项目。

为了从n个输入及其各自的计数中产生公共输入,我们使用most_common()函数。import collections

c = collections.Counter()

texts = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in

reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa

qui officia deserunt mollit anim id est laborum.'''

for word in texts:

c.update(word.rstrip().lower())

print("Five most common letters in the texts: ")

for letter, count in c.most_common(5):

print("%s: %7d" %(letter, count))

输出结果Five most common letters in the texts:

i: 42

e: 38

t: 32

o: 29

u: 29

上面的示例对出现在文本(或您可以考虑使用的文件)中的字母进行计数以产生频率分布,然后打印出最常见的五个字母。将参数保留给most_common()会按频率顺序生成所有项目的列表。

算术

计数器实例支持算术运算和设置运算以汇总结果。import collections

c1 = collections.Counter(['a', 'b', 'c', 'a' ,'b', 'b'])

c2 = collections.Counter('alphabet')

print('C1: ', c1)

print('C2: ', c2)

print ('\nCombined counts: ')

print(c1 + c2)

print('\nSubtraction: ')

print(c1 - c2)

print('\nIntersection (taking positive minimums): ')

print(c1 & c2)

print('\nUnion (taking maximums): ')

print(c1 | c2)

输出结果C1: Counter({'b': 3, 'a': 2, 'c': 1})

C2: Counter({'a': 2, 'l': 1, 'p': 1, 'h': 1, 'b': 1, 'e': 1, 't': 1})

Combined counts:

Counter({'a': 4, 'b': 4, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})

Subtraction:

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

Intersection (taking positive minimums):

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

Union (taking maximums):

Counter({'b': 3, 'a': 2, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})

每次通过操作产生一个新的计数器时,任何计数为零或负的项目都将被丢弃。