Python计数器– Python集合计数器

时间:2020-02-23 14:42:34  来源:igfitidea点击:

Python Counter类是Collections模块的一部分。
Counter是Dictionary的子类,用于跟踪元素及其数量。

Python计数器

计数器是一个无序集合,其中元素存储为Dict键,其计数为dict值。

计数器元素count可以为正,零或者负整数。
但是,对其键和值没有任何限制。
尽管值旨在为数字,但我们也可以存储其他对象。

创建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作为创建Counter对象的参数。
因此字符串文字和列表也可以用于创建Counter对象。

# 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='hyman', age=20)
print(special_counter)  # Counter({'name': 'hyman', '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})

从Counter删除元素

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

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

elements()

此方法返回计数器中的元素列表。
仅返回具有正计数的元素。

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)

上面的代码将两次打印" Dog",因为它的计数为2。
其他元素由于没有正数而将被忽略。
Counter是无序集合,因此元素没有特定的顺序返回。

most_common(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)]

减去()和更新()

Countersubtract()方法用于从另一个计数器中减去元素计数。
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计数器算术运算

我们也可以像数字一样在Counters上执行一些算术运算。
但是,这些操作仅返回具有正计数的元素。

# 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()