Python 中的计数器?
计数器是一个容器,用于跟踪等值添加的次数。Python 计数器类是集合模块的一部分,是字典的子类。
Python 计数器
我们可以将计数器视为无序的项目集合,其中项目存储为字典键,其计数存储为字典值。
计数器项目计数可以是正整数、零整数或负整数。虽然对其键和值没有限制,但通常值应为数字,但我们也可以存储其他对象类型。
初始化
计数器支持三种初始化形式。可以使用项目序列、包含键和计数的字典或使用将字符串名称映射到计数的关键字参数来调用其构造函数。
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})
要创建一个空计数器,请传递不带参数的计数器并通过更新方法填充它。
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
Counter 不会对未知项(如我们在上述程序中提到的项 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})
每次通过操作产生新的计数器时,任何计数为零或负数的项目都会被丢弃。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

