python对象引用计数器_在Python中借助计数器对象对项目进行计数
python對(duì)象引用計(jì)數(shù)器
前提 (The Premise)
When we deal with data containers, such as tuples and lists, in Python we often need to count particular elements. One common way to do this is to use the count() function — you specify the element you want to count and the function returns the count.
當(dāng)我們?cè)赑ython中處理數(shù)據(jù)容器(例如元組和列表)時(shí),我們經(jīng)常需要計(jì)算特定元素。 一種常見的實(shí)現(xiàn)方法是使用count()函數(shù)-您指定要計(jì)數(shù)的元素,然后該函數(shù)返回計(jì)數(shù)。
Let’s take a look at some code for its use:
讓我們看一些使用它的代碼:
The count() functioncount()函數(shù)As you can see above, we used the count() function with a list of scores.
如上所示,我們將count()函數(shù)與分?jǐn)?shù)列表一起使用。
One thing to note: When the elements specified in the function aren’t included in the list, we’ll get a count of zero, as expected. If we want to count the occurrences of all the elements, we’ll have to iterate them, as shown in the following code snippet:
需要注意的一件事:如果函數(shù)中指定的元素未包含在列表中,我們將得到預(yù)期的零計(jì)數(shù)。 如果要計(jì)算所有元素的出現(xiàn)次數(shù),則必須對(duì)其進(jìn)行迭代,如以下代碼片段所示:
Count All Elements計(jì)算所有元素Several things are worth highlighting in the above:
上面值得強(qiáng)調(diào)的幾件事:
To avoid counting elements of the same value, we use the set() constructor to convert these iterables to set objects. This means duplicate elements are removed — the for loop will only go over distinct elements to get their correct cumulative counts.
為了避免計(jì)數(shù)相同值的元素,我們使用set()構(gòu)造函數(shù)將這些可迭代對(duì)象轉(zhuǎn)換為set對(duì)象。 這意味著刪除了重復(fù)的元素-for循環(huán)將僅遍歷不同的元素以獲得正確的累計(jì)計(jì)數(shù)。
The count() function doesn’t only work with the list objects, it can also with tuples and strings. More generally, the count() function works with sequence data in Python, including strings, lists, tuples, and bytes.
count()函數(shù)不僅適用于列表對(duì)象,還適用于元組和字符串。 更一般而言, count()函數(shù)可用于Python中的序列數(shù)據(jù),包括字符串,列表,元組和字節(jié)。
As shown above, we have to use a for loop to iterate the elements to retrieve the counts for each individual element. It’s a bit tedious.
如上所示,我們必須使用for循環(huán)來(lái)迭代元素以檢索每個(gè)單獨(dú)元素的計(jì)數(shù)。 這有點(diǎn)乏味。
Is there another, better way to solve the problem? If you know Python, you should guess that the answer is yes. The Counter class is specifically designed to count elements in these data structures.
是否有另一種更好的方法來(lái)解決該問題? 如果您了解Python,則應(yīng)該猜測(cè)答案是肯定的。 Counter類專門設(shè)計(jì)用于對(duì)這些數(shù)據(jù)結(jié)構(gòu)中的元素進(jìn)行計(jì)數(shù)。
柜臺(tái)類-概述 (The Counter Class — Overview)
The Counter class is available through the collections module as part of Python’s standard library. As a subclass of the dict class, it provides a few highly specialized methods that handle object counting. To create a counter object, you can simply set an iterable to the Counter class instance constructor, as shown:
Counter類可作為Python標(biāo)準(zhǔn)庫(kù)的一部分通過(guò)collections模塊獲得。 作為dict類的子類,它提供了一些處理對(duì)象計(jì)數(shù)的高度專業(yè)化的方法。 要?jiǎng)?chuàng)建一個(gè)計(jì)數(shù)器對(duì)象,您可以簡(jiǎn)單地將一個(gè)Iterable設(shè)置為Counter類實(shí)例構(gòu)造函數(shù),如下所示:
Counter Object Creation計(jì)數(shù)器對(duì)象創(chuàng)建As you can see at line seven, a Counter object looks like a dictionary with a series of key-value pairs. Specifically, the keys are the counted elements, while the values are the counters for the corresponding keys. If you want to retrieve the counts for individual items, you can do that just as you work with a dictionary. Some trivial examples are shown below. Notably, if the key doesn’t exist in the Counter object, the count will be zero.
如您在第七行看到的, Counter對(duì)象看起來(lái)像是帶有一系列鍵值對(duì)的字典。 具體來(lái)說(shuō),鍵是被計(jì)數(shù)的元素,而值是對(duì)應(yīng)鍵的計(jì)數(shù)器。 如果要檢索單個(gè)項(xiàng)目的計(jì)數(shù),則可以像處理字典一樣進(jìn)行。 一些簡(jiǎn)單的示例如下所示。 值得注意的是,如果Counter對(duì)象中不存在鍵,則計(jì)數(shù)將為零。
Access Individual Items訪問單個(gè)項(xiàng)目One critical thing to note is that because of the key-value mapping mechanism, only hashable objects can be tracked by a Counter object. In Python, immutable objects, such as strings, integers, and tuples are all hashable, while mutable objects, such as lists, sets, and dictionaries are unhashable. A detailed discussion of object hashability is beyond the scope of the present article, and if you’re interested, you can find more information in my previous article on this topic.
需要注意的關(guān)鍵一點(diǎn)是,由于鍵值映射機(jī)制, Counter對(duì)象只能跟蹤可哈希對(duì)象。 在Python中,不可變對(duì)象(例如字符串,整數(shù)和元組)都是可哈希的,而可變對(duì)象(例如列表,集合和字典)則不可哈希。 關(guān)于對(duì)象散列性的詳細(xì)討論超出了本文的范圍,并且如果您有興趣,可以在我上一篇有關(guān)該主題的文章中找到更多信息。
The following code shows you a trivial example when we try to use Counter with unhashable objects — lists. The error message clearly tells us that Python cannot instantiate a Counter object for us because lists are unhashable objects in Python.
以下代碼向您展示了一個(gè)簡(jiǎn)單的示例,當(dāng)我們嘗試將Counter與不可哈希對(duì)象一起使用時(shí)- lists 。 該錯(cuò)誤消息清楚地告訴我們,Python無(wú)法為我們實(shí)例化Counter對(duì)象,因?yàn)閘ists在Python lists是不可散列的對(duì)象。
Unhashable — Counter無(wú)法散列-計(jì)數(shù)器確定最頻繁的項(xiàng)目 (Determine the Most Frequent Items)
Often, we need to know what the frequently occurring items in a data container (e.g., lists and tuples) are. Before we see the solution with the Counter object, let’s see how to achieve this functionality using some tedious code:
通常,我們需要知道數(shù)據(jù)容器(例如列表和元組)中經(jīng)常出現(xiàn)的項(xiàng)目是什么。 在看到帶有Counter對(duì)象的解決方案之前,讓我們看一下如何使用一些乏味的代碼來(lái)實(shí)現(xiàn)此功能:
The Non-Idiomatic Way非慣用方式As shown above, we first needed to use the list’s count() method to count each of the unique items in the list and save the counting result to a dictionary. Next, we had to use the built-in max() function to sort the items of the dictionary by specifying the sorting key to use the value of each key-value pair. Certainly, this way works but it’s not the idiomatic way, in which case, we should consider using Counter.
如上所示,我們首先需要使用列表的count()方法對(duì)列表中的每個(gè)唯一項(xiàng)進(jìn)行計(jì)數(shù),并將計(jì)數(shù)結(jié)果保存到字典中。 接下來(lái),我們必須使用內(nèi)置的max()函數(shù)通過(guò)指定排序鍵以使用每個(gè)鍵值對(duì)的值來(lái)對(duì)字典中的項(xiàng)進(jìn)行排序。 當(dāng)然,這種方法可行,但不是慣用的方法,在這種情況下,我們應(yīng)該考慮使用Counter 。
Most Frequent Item最常出現(xiàn)的項(xiàng)目As shown above, the first impression that you should have is how concise the code is compared to the non-idiomatic implementation of this functionality. It’s all because the Counter object has a handy most_common() method, which quickly pulls the needed information for us — the most frequently occurring item and its associated count. Actually, to give us more flexibility, we have the option to find out an arbitrary number of the most frequently occurring items, as shown below.
如上所示,您應(yīng)該獲得的第一印象是將代碼的簡(jiǎn)潔程度與該功能的非慣用實(shí)現(xiàn)相比。 這是因?yàn)镃ounter對(duì)象有一個(gè)方便的most_common()方法,該方法可以為我們快速獲取所需的信息-最頻繁出現(xiàn)的項(xiàng)目及其相關(guān)計(jì)數(shù)。 實(shí)際上,為給我們更大的靈活性,我們可以選擇找出任意數(shù)量的最頻繁出現(xiàn)的項(xiàng)目,如下所示。
Most Frequent Items最常見的物品Please note that when you don’t specify any numbers in the most_common() method, all the elements will be returned as a list in the descending order of the counts. This descending order can be very useful, which allows us to retrieve the item with the least count, as shown below.
請(qǐng)注意,當(dāng)您未在most_common()方法中指定任何數(shù)字時(shí),所有元素都將按照計(jì)數(shù)的降序作為列表返回。 降序可能非常有用,這使我們可以檢索數(shù)量最少的商品,如下所示。
Least Frequent Item最少的頻繁項(xiàng)目更新計(jì)數(shù)器對(duì)象 (Update the Counter Object)
Previously, we saw that the Counter object is used to count the elements in a list. But what if we get another list and want to update the original Counter object without creating a new one?
之前,我們看到了Counter對(duì)象用于對(duì)列表中的元素進(jìn)行計(jì)數(shù)。 但是,如果我們得到另一個(gè)列表并想要更新原始的Counter對(duì)象而不創(chuàng)建一個(gè)新的對(duì)象,該怎么辦?
One possible solution is to take advantage of a Counter object, implementing the mapping protocol such that we can update each key’s value accordingly. Notably, if the key doesn’t exist in the original Counter object, unlike the built-in dict data type, a KeyValue exception won’t be raised, because by default, a missing key in a Counter object has a value of 0, as we saw with accessing individual items.
一種可能的解決方案是利用Counter對(duì)象,實(shí)現(xiàn)映射協(xié)議,以便我們可以相應(yīng)地更新每個(gè)鍵的值。 值得注意的是,如果鍵不存在于原始Counter對(duì)象中(與內(nèi)置dict數(shù)據(jù)類型不同),則不會(huì)引發(fā)KeyValue異常,因?yàn)槟J(rèn)情況下, Counter對(duì)象中缺少的鍵的值為0 ,正如我們?cè)谠L問單個(gè)項(xiàng)目時(shí)看到的那樣。
Update Counter Object更新計(jì)數(shù)器對(duì)象There’s a more elegant way to update the original Counter object — use the Counter’s update() method. Don’t confuse this update() method with the dict’s update() method, which updates the values of matching keys. Instead, the Counter’s update() method will internally generate the counts for the items and use these counts to update the original Counter object, as shown in the code snippet below.
有一種更優(yōu)雅的方式來(lái)更新原始的Counter對(duì)象-使用Counter的update()方法。 不要將此update()方法與dict'的update()方法混淆,后者會(huì)更新匹配鍵的值。 相反, Counter的update()方法將在內(nèi)部生成項(xiàng)目的計(jì)數(shù),并使用這些計(jì)數(shù)來(lái)更新原始的Counter對(duì)象,如下面的代碼片段所示。
The update() Methodupdate()方法數(shù)學(xué)運(yùn)算 (Mathematical Operations)
The name of the Counter class is informational, which tells you that it counts for us. As we’ve seen, we can update the counts with the update() method. More broadly, when we have multiple Counter objects, we can have addition and subtraction operations with them. When we add Counter objects, the counts for the elements are merged.
Counter類的名稱是參考性的,它告訴您它對(duì)我們很重要。 如我們所見,我們可以使用update()方法更新計(jì)數(shù)。 更廣泛地說(shuō),當(dāng)我們有多個(gè)Counter對(duì)象時(shí),我們可以對(duì)其進(jìn)行加減運(yùn)算。 當(dāng)我們添加Counter對(duì)象時(shí),元素的計(jì)數(shù)將合并。
The following code shows you such operation, which should be self-explanatory:
下面的代碼向您展示了這樣的操作,這應(yīng)該是不言而喻的:
Addition of Counter Objects添加計(jì)數(shù)器對(duì)象In a similar fashion, we can subtract one Counter object from another Counter object using the minus operator, as shown below.
以類似的方式,我們可以使用減號(hào)運(yùn)算符從另一個(gè)Counter對(duì)象中減去一個(gè)Counter對(duì)象,如下所示。
Subtraction of Counter Objects相減對(duì)象In the above code, one thing to note is that when we use the subtraction operator, the resulting Counter object will only include those key-value pairs with positive counts. This behavior is different from Counter’s method subtract(), which will also include negative counts. Also, as noted previously, when a Counter doesn’t contain the elements, they have a count of zero by default. With these two things in mind, let’s see how the subtract() method works with Counter objects.
在上面的代碼中,需要注意的一件事是,當(dāng)我們使用減法運(yùn)算符時(shí),所得的Counter對(duì)象將僅包括具有正計(jì)數(shù)的那些鍵值對(duì)。 此行為不同于Counter的方法subtract() ,該方法還將包括負(fù)數(shù)。 另外,如前所述,當(dāng)Counter不包含元素時(shí),默認(rèn)情況下它們的計(jì)數(shù)為零。 牢記這兩點(diǎn),讓我們看一下subtract()方法如何與Counter對(duì)象一起工作。
The subtract() Method減去()方法As you can see, the resulting Counter object includes several elements with negative counts. Another thing to note is that the subtract() method changes the counts in-place, which means that the subtract() method returns None and it changes the original Counter object’s counts.
如您所見,生成的Counter對(duì)象包含多個(gè)帶有負(fù)計(jì)數(shù)的元素。 還要注意的另一件事是subtract()方法就地更改了計(jì)數(shù),這意味著subtract()方法將返回None并且它會(huì)更改原始Counter對(duì)象的計(jì)數(shù)。
集樣操作 (Set-Like Operations)
In addition to the support of mathematical operations, there are two set-like operations available to the Counter objects: union and intersection. To create a “union” of two Counter objects, you simply use the OR operator (i.e., the vertical bar) to connect them. The union operation will be carried out by using the maximal counts of each matching key in the resulting Counter object. A trivial example is shown below:
除了支持?jǐn)?shù)學(xué)運(yùn)算外, Counter對(duì)象還可以使用兩種類似集合的運(yùn)算: union和intersection 。 要?jiǎng)?chuàng)建兩個(gè)Counter對(duì)象的“聯(lián)合”,只需使用OR運(yùn)算符(即,豎線)將它們連接。 聯(lián)合操作將通過(guò)使用結(jié)果Counter對(duì)象中每個(gè)匹配鍵的最大計(jì)數(shù)來(lái)執(zhí)行。 一個(gè)簡(jiǎn)單的示例如下所示:
Union of Counters柜臺(tái)聯(lián)盟To create an “intersection” of two Counter objects, you’ll simply use the AND operator (i.e. the & sign) to connect them. The intersection operation will be carried out by using the minimal counts of each matching key in the resulting Counter object. A trivial example is shown below.
要?jiǎng)?chuàng)建兩個(gè)Counter對(duì)象的“交集”,只需使用AND運(yùn)算符(即&符號(hào))將它們連接起來(lái)。 將通過(guò)使用結(jié)果Counter對(duì)象中每個(gè)匹配鍵的最小計(jì)數(shù)來(lái)執(zhí)行相交操作。 一個(gè)簡(jiǎn)單的例子如下所示。
Intersection of Counters柜臺(tái)相交其他功能亮點(diǎn) (Highlights of Other Features)
In the previous sections, we learned that we can create Counter objects from iterables, including tuples, lists, and strings. As mentioned previously, the Counter class is a subclass of the built-in dict class, so we can use instantiation methods that are available to the dict class. Some examples are shown below with accompanying explanatory comments:
在上一節(jié)中,我們了解了可以從可迭代對(duì)象(包括元組,列表和字符串)創(chuàng)建Counter對(duì)象。 如前所述, Counter類是內(nèi)置dict類的子類,因此我們可以使用dict類可用的實(shí)例化方法。 下面顯示了一些示例,并附有解釋性注釋:
Construct Counters建造柜臺(tái)We’ve seen that the counts of the Counter objects are derived from counting or mathematical operations. We can directly set the count of particular elements if it’s an applicable usage. In addition, we can remove the elements from the Counter object, just like removing a key-value pair from a dict object. See below for such usages:
我們已經(jīng)看到, Counter對(duì)象的計(jì)數(shù)是從計(jì)數(shù)或數(shù)學(xué)運(yùn)算得出的。 如果可以使用的話,我們可以直接設(shè)置特定元素的數(shù)量。 另外,我們可以從Counter對(duì)象中刪除元素,就像從dict對(duì)象中刪除鍵/值對(duì)一樣。 參見下面的用法:
Manipulate Counter Objects操作計(jì)數(shù)器對(duì)象Another useful method of a Counter object is the elements() method, which creates an iterator of all items with each having the desired occurrences matching its count. This method is particularly handy for iterating different items of known numbers.
Counter對(duì)象的另一個(gè)有用的方法是elements()方法,該方法創(chuàng)建所有項(xiàng)目的迭代器,每個(gè)項(xiàng)目都具有與其計(jì)數(shù)匹配的期望出現(xiàn)次數(shù)。 該方法對(duì)于迭代已知數(shù)字的不同項(xiàng)特別方便。
The elements() Methodelements()方法結(jié)論 (Conclusions)
In this article, we reviewed the interesting Counter class for counting hashable objects in sequences, including tuples, lists, and strings. As a subclass of the dict data type, we can create Counter objects from the sequences as well as mapping and keyword arguments, just as regular dict objects. The Counter object is highly flexible in that you can manipulate the counts of these elements as you want. You can even update, merge, and intersect Counter objects.
在本文中,我們回顧了有趣的Counter類,用于對(duì)序列中的可哈希對(duì)象進(jìn)行計(jì)數(shù),包括元組,列表和字符串。 作為dict數(shù)據(jù)類型的子類,我們可以像常規(guī)dict對(duì)象一樣,從序列以及映射和關(guān)鍵字參數(shù)中創(chuàng)建Counter對(duì)象。 Counter對(duì)象具有高度的靈活性,因?yàn)槟梢愿鶕?jù)需要操縱這些元素的計(jì)數(shù)。 您甚至可以更新,合并和相交Counter對(duì)象。
Most interestingly, it has the most_common() method, which allows us to find out the most frequent items with one line of code. It’s also possible to find out the least frequent items by taking advantage of the most_common() method, which sorts the items in descending order, allowing us to retrieve the last item for the least common item.
最有趣的是,它具有most_common()方法,該方法使我們可以用一行代碼找出最頻繁的項(xiàng)目。 也可以利用most_common()方法找出最不頻繁的項(xiàng)目,該方法以降序?qū)?xiàng)目進(jìn)行排序,從而使我們能夠檢索最不常見項(xiàng)目的最后一個(gè)項(xiàng)目。
Thanks for reading.
謝謝閱讀。
翻譯自: https://medium.com/better-programming/count-items-in-python-with-the-help-of-counter-objects-c08d8d486e45
python對(duì)象引用計(jì)數(shù)器
總結(jié)
以上是生活随笔為你收集整理的python对象引用计数器_在Python中借助计数器对象对项目进行计数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到包包子吃包子是啥意思
- 下一篇: 数字图像处理 python_5使用Pyt