Python计数器 – Python集合计数器

Python Collections 模块中包含了 Counter 类。Counter 是 Dictionary 的一个子类,用于跟踪元素及其计数。

Python计数器

计数器是无序集合,其中元素被存储为字典键,它们的计数作为字典值。计数器元素的计数可以是正数、零或负整数。但是它的键和值没有任何限制。尽管值通常是数字,但我们也可以存储其他对象。

创建Python的Counter对象

我们可以创建一个空的计数器,也可以从一些初始值开始。

from collections import Counter

# empty Counter
counter = Counter()
print(counter)  # Counter()

# Counter with initial values
counter = Counter(['a', 'a', 'b'])
print(counter)  # Counter({'a': 2, 'b': 1})

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

我们还可以使用任何可迭代对象作为创建计数器对象的参数。因此,字符串文字和列表也可以用于创建计数器对象。

# Iterable as argument for Counter
counter = Counter('abc')
print(counter)  # Counter({'a': 1, 'b': 1, 'c': 1})

# List as argument to Counter
words_list = ['Cat', 'Dog', 'Horse', 'Dog']
counter = Counter(words_list)
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})

# Dictionary as argument to Counter
word_count_dict = {'Dog': 2, 'Cat': 1, 'Horse': 1}
counter = Counter(word_count_dict)
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})

如我上面所提到的,我们也可以使用非数值数据作为计数值,但这会违背Counter类的初衷。

# Counter works with non-numbers too
special_counter = Counter(name='Pankaj', age=20)
print(special_counter)  # Counter({'name': 'Pankaj', 'age': 20})

Python计数器方法

让我们来了解一下Counter类的方法以及我们可以对其执行的其他操作。

获取元素的数量

# getting count
counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
countDog = counter['Dog']
print(countDog)  # 2

如果我们尝试获取一个不存在的键的计数,它将返回0而不会引发KeyError。

# getting count for non existing key, don't cause KeyError
print(counter['Unicorn'])  # 0

元素数量设置

我们还可以设置计数器中已存在元素的数量。如果该元素不存在,则会被添加到计数器中。

counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
# setting count
counter['Horse'] = 0
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})

# setting count for non-existing key, adds to Counter
counter['Unicorn'] = 1
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Unicorn': 1, 'Horse': 0})

从计数器中删除一个元素

我们可以使用del来从计数器对象中删除元素。

# Delete element from Counter
del counter['Unicorn']
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})

元素()

这个方法返回计数器中的元素列表。只返回计数大于零的元素。

counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})

# elements()
elements = counter.elements()  # doesn't return elements with count 0 or less
for value in elements:
    print(value)

上述代码会打印“狗”两次,因为它的计数为2。其他元素将被忽略,因为它们没有正数计数。计数器是一个无序集合,所以元素的返回顺序并不确定。

最常见的(n)

这个方法从计数器中返回最常见的元素。如果我们不提供‘n’的值,那么会返回从最常见到最不常见的元素的排序字典。我们可以使用切片来获取排序字典中最不常见的元素。

counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})

# most_common()
most_common_element = counter.most_common(1)
print(most_common_element)  # [('Dog', 2)]

least_common_element = counter.most_common()[:-2:-1]
print(least_common_element)  # [('Cat', -1)]

减去()和更新()

计数器的subtract()方法用于从另一个计数器中减去元素计数。update()方法用于从另一个计数器中添加计数。

counter = Counter('ababab')
print(counter)  # Counter({'a': 3, 'b': 3})
c = Counter('abc')
print(c)  # Counter({'a': 1, 'b': 1, 'c': 1})

# subtract
counter.subtract(c)
print(counter)  # Counter({'a': 2, 'b': 2, 'c': -1})

# update
counter.update(c)
print(counter)  # Counter({'a': 3, 'b': 3, 'c': 0})

Python Counter算术运算

我们也可以对计数器执行一些算术运算,就像对数字一样。然而,只有计数为正的元素才会返回这些操作的结果。

# arithmetic operations
c1 = Counter(a=2, b=0, c=-1)
c2 = Counter(a=1, b=-1, c=2)

c = c1 + c2  # return items having +ve count only
print(c)  # Counter({'a': 3, 'c': 1})

c = c1 - c2  # keeps only +ve count elements
print(c)  # Counter({'a': 1, 'b': 1})

c = c1 & c2  # intersection min(c1[x], c2[x])
print(c)  # Counter({'a': 1})

c = c1 | c2  # union max(c1[x], c2[x])
print(c)  # Counter({'a': 2, 'c': 2})

对Python Counter进行的各种操作

让我们来看一些可以在计数器对象上执行的杂项操作的代码片段。

counter = Counter({'a': 3, 'b': 3, 'c': 0})
# miscellaneous examples
print(sum(counter.values()))  # 6

print(list(counter))  # ['a', 'b', 'c']
print(set(counter))  # {'a', 'b', 'c'}
print(dict(counter))  # {'a': 3, 'b': 3, 'c': 0}
print(counter.items())  # dict_items([('a', 3), ('b', 3), ('c', 0)])

# remove 0 or negative count elements
counter = Counter(a=2, b=3, c=-1, d=0)
counter = +counter
print(counter)  # Counter({'b': 3, 'a': 2})

# clear all elements
counter.clear()
print(counter)  # Counter()

对于Python Counter类,就这些了。

你可以从我的GitHub存储库下载完整的示例代码。

参考:Python文档

发表回复 0

Your email address will not be published. Required fields are marked *