Python Counter 类是 Collections模块的一部分。 Counter 是 Dictionary的子类,用于跟踪元素及其计数。
Python 计数器
Counter 是一个未分类的集合,其中元素被存储为Dict
键,而它们的计数作为Dict值。 Counter 元素的计数可以是正数、零或负数的整数。
创建 Python 反对对象
我们可以创建一个空数或开始一些初始值。
1from collections import Counter
2
3# empty Counter
4counter = Counter()
5print(counter) # Counter()
6
7# Counter with initial values
8counter = Counter(['a', 'a', 'b'])
9print(counter) # Counter({'a': 2, 'b': 1})
10
11counter = Counter(a=2, b=3, c=1)
12print(counter) # Counter({'b': 3, 'a': 2, 'c': 1})
我们也可以使用任何Iterable作为创建 Counter 对象的论点,因此 字母字符串和 List也可以用于创建 Counter 对象。
1# Iterable as argument for Counter
2counter = Counter('abc')
3print(counter) # Counter({'a': 1, 'b': 1, 'c': 1})
4
5# List as argument to Counter
6words_list = ['Cat', 'Dog', 'Horse', 'Dog']
7counter = Counter(words_list)
8print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
9
10# Dictionary as argument to Counter
11word_count_dict = {'Dog': 2, 'Cat': 1, 'Horse': 1}
12counter = Counter(word_count_dict)
13print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
正如我上面提到的,我们也可以使用非数字数据来计数值,但这会破坏 Counter 类的目的。
1# Counter works with non-numbers too
2special_counter = Counter(name='Pankaj', age=20)
3print(special_counter) # Counter({'name': 'Pankaj', 'age': 20})
Python 反对方法
让我们看看反对类方法和我们可以执行的其他一些操作。
得到元素的数目
1# getting count
2counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
3countDog = counter['Dog']
4print(countDog) # 2
如果我们试图获得不存在的密钥的计数,它将返回0并不会扔KeyError
。
1# getting count for non existing key, don't cause KeyError
2print(counter['Unicorn']) # 0
设置元素数
我们还可以设置计数器中现有的元素的数值,如果元素不存在,那么它会被添加到计数器中。
1counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
2# setting count
3counter['Horse'] = 0
4print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})
5
6# setting count for non-existing key, adds to Counter
7counter['Unicorn'] = 1
8print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Unicorn': 1, 'Horse': 0})
从计数中删除一个元素
我们可以使用del
来从计数对象中删除一个元素。
1# Delete element from Counter
2del counter['Unicorn']
3print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})
元素()
此方法返回计数器中的元素列表. 只返回有正数的元素。
1counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})
2
3# elements()
4elements = counter.elements() # doesn't return elements with count 0 or less
5for value in elements:
6 print(value)
上面的代码将打印狗
两次,因为它的计数是2。其他元素将被忽略,因为它们没有正数。
最常见(n)
此方法返回最常见的元素从计数器. 如果我们不提供n
的值,那么排序字典返回最常见的最不常见的元素. 我们可以使用切割来获取这个排序字典中最不常见的元素。
1counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})
2
3# most_common()
4most_common_element = counter.most_common(1)
5print(most_common_element) # [('Dog', 2)]
6
7least_common_element = counter.most_common()[:-2:-1]
8print(least_common_element) # [('Cat', -1)]
subtract() 和更新()
Counter subtract()
方法用于从另一个计数中提取元素数。
1counter = Counter('ababab')
2print(counter) # Counter({'a': 3, 'b': 3})
3c = Counter('abc')
4print(c) # Counter({'a': 1, 'b': 1, 'c': 1})
5
6# subtract
7counter.subtract(c)
8print(counter) # Counter({'a': 2, 'b': 2, 'c': -1})
9
10# update
11counter.update(c)
12print(counter) # Counter({'a': 3, 'b': 3, 'c': 0})
Python 反算术操作
我们也可以在计数器上执行一些算术操作,就像数字一样,但是只有具有正数的元素才能返回这些操作。
1# arithmetic operations
2c1 = Counter(a=2, b=0, c=-1)
3c2 = Counter(a=1, b=-1, c=2)
4
5c = c1 + c2 # return items having +ve count only
6print(c) # Counter({'a': 3, 'c': 1})
7
8c = c1 - c2 # keeps only +ve count elements
9print(c) # Counter({'a': 1, 'b': 1})
10
11c = c1 & c2 # intersection min(c1[x], c2[x])
12print(c) # Counter({'a': 1})
13
14c = c1 | c2 # union max(c1[x], c2[x])
15print(c) # Counter({'a': 2, 'c': 2})
在 Python Counter 上进行混乱的操作
让我们看看我们可以在反对对象上执行的不同操作的某些代码片段。
1counter = Counter({'a': 3, 'b': 3, 'c': 0})
2# miscellaneous examples
3print(sum(counter.values())) # 6
4
5print(list(counter)) # ['a', 'b', 'c']
6print(set(counter)) # {'a', 'b', 'c'}
7print(dict(counter)) # {'a': 3, 'b': 3, 'c': 0}
8print(counter.items()) # dict_items([('a', 3), ('b', 3), ('c', 0)])
9
10# remove 0 or negative count elements
11counter = Counter(a=2, b=3, c=-1, d=0)
12counter = +counter
13print(counter) # Counter({'b': 3, 'a': 2})
14
15# clear all elements
16counter.clear()
17print(counter) # Counter()
这就是Python Counter类的一切。
您可以从我的 GitHub 存储库下载完整的示例代码。
参考: Python 文档