手机怎么安装py thon

Python Counter class is part of Collections module. Counter is a subclass of Dictionary and used to keep track of elements and their count.

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

(Python Counter)

Counter is an unordered collection where elements are stored as Dict keys and their count as dict value.

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

Counter elements count can be positive, zero or negative integers. However there is no restriction on it’s keys and values. Although values are intended to be numbers but we can store other objects too.

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

(Creating Python Counter Object)

We can create an empty Counter or start with some initial values too.

我们可以创建一个空的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})

We can also use any Iterable as argument for creating Counter object. So string literal and List can be used too for creating Counter object.

我们还可以使用任何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})

As I mentioned above, we can use non-numeric data for count values too, but that will defect the purpose of Counter class.

正如我上面提到的,我们也可以将非数字数据用于计数值,但是这会抵消Counter类的用途。

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

(Python Counter Methods)

Let’s look into Counter class methods and some other operations we can perform on it.

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

(Getting Count of Elements)

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

If we try to get the count of non-existing key, it will return 0 and not throw KeyError.

如果我们尝试获取不存在的键的计数,它将返回0而不抛出KeyError

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

(Setting Count of Elements)

We can also set the count of existing element in the counter. If the element doesn’t exist, then it gets added to the counter.

我们还可以设置计数器中现有元素的计数。 如果该元素不存在,则将其添加到计数器。


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})

(Deleting an element from Counter)

We can use del to delete an element from the counter object.

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

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

(elements())

This method returns the list of elements in the counter. Only elements with positive counts are returned.

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

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)

Above code will print “Dog” two times because it’s count is 2. Other elements will be ignored because they don’t have positive count. Counter is an unordered collection, so elements are returned in no particular order.

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

(most_common(n))

This method returns the most common elements from the counter. If we don’t provide value of ‘n’ then sorted dictionary is returned from most common the least common elements. We can use slicing to get the least common elements on this sorted dictionary.

此方法从计数器返回最常见的元素。 如果我们不提供'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() and update())

Counter subtract() method is used to subtract element counts from another counter. update() method is used to add counts from another counter.

计数器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)

We can perform some arithmetic operations on Counters too, just like numbers. However only elements with positive count are returned with these operations.

我们也可以像数字一样在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})

(Miscellaneous Operations on Python Counter)

Let’s look at some code snippets for miscellaneous operations we can perform on Counter objects.

让我们看一下一些可以在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()

That’s all for Python Counter class.

这就是Python Counter类的全部内容。

GitHub Repository. GitHub Repository下载完整的示例代码。



Reference: Python Docs

参考: Python文档

翻译自: https://www.journaldev.com/20806/python-counter-python-collections-counter

手机怎么安装py thon