python對象引用計數器_在Python中借助計數器對象對項目進行計數

python對象引用計數器

前提 (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.

當我們在Python中處理數據容器(例如元組和列表)時,我們經常需要計算特定元素。 一種常見的實現方法是使用count()函數-您指定要計數的元素,然后該函數返回計數。

Let’s take a look at some code for its use:

讓我們看一些使用它的代碼:

The count() function
count()函數

As you can see above, we used the count() function with a list of scores.

如上所示,我們將count()函數與分數列表一起使用。

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:

需要注意的一件事:如果函數中指定的元素未包含在列表中,我們將得到預期的零計數。 如果要計算所有元素的出現次數,則必須對其進行迭代,如以下代碼片段所示:

Count All Elements
計算所有元素

Several things are worth highlighting in the above:

上面值得強調的幾件事:

  • 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.

    為了避免計數相同值的元素,我們使用set()構造函數將這些可迭代對象轉換為set對象。 這意味著刪除了重復的元素-for循環將僅遍歷不同的元素以獲得正確的累計計數。

  • 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()函數不僅適用于列表對象,還適用于元組和字符串。 更一般而言, count()函數可用于Python中的序列數據,包括字符串,列表,元組和字節。

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循環來迭代元素以檢索每個單獨元素的計數。 這有點乏味。

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.

是否有另一種更好的方法來解決該問題? 如果您了解Python,則應該猜測答案是肯定的。 Counter類專門設計用于對這些數據結構中的元素進行計數。

柜臺類-概述 (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標準庫的一部分通過collections模塊獲得。 作為dict類的子類,它提供了一些處理對象計數的高度專業化的方法。 要創建一個計數器對象,您可以簡單地將一個Iterable設置為Counter類實例構造函數,如下所示:

Counter Object Creation
計數器對象創建

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對象看起來像是帶有一系列鍵值對的字典。 具體來說,鍵是被計數的元素,而值是對應鍵的計數器。 如果要檢索單個項目的計數,則可以像處理字典一樣進行。 一些簡單的示例如下所示。 值得注意的是,如果Counter對象中不存在鍵,則計數將為零。

Access Individual Items
訪問單個項目

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.

需要注意的關鍵一點是,由于鍵值映射機制, Counter對象只能跟蹤可哈希對象。 在Python中,不可變對象(例如字符串,整數和元組)都是可哈希的,而可變對象(例如列表,集合和字典)則不可哈希。 關于對象散列性的詳細討論超出了本文的范圍,并且如果您有興趣,可以在我上一篇有關該主題的文章中找到更多信息。

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.

以下代碼向您展示了一個簡單的示例,當我們嘗試將Counter與不可哈希對象一起使用時- lists 。 該錯誤消息清楚地告訴我們,Python無法為我們實例化Counter對象,因為lists在Python lists是不可散列的對象。

Unhashable — Counter
無法散列-計數器

確定最頻繁的項目 (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:

通常,我們需要知道數據容器(例如列表和元組)中經常出現的項目是什么。 在看到帶有Counter對象的解決方案之前,讓我們看一下如何使用一些乏味的代碼來實現此功能:

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()方法對列表中的每個唯一項進行計數,并將計數結果保存到字典中。 接下來,我們必須使用內置的max()函數通過指定排序鍵以使用每個鍵值對的值來對字典中的項進行排序。 當然,這種方法可行,但不是慣用的方法,在這種情況下,我們應該考慮使用Counter

Most Frequent Item
最常出現的項目

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.

如上所示,您應該獲得的第一印象是將代碼的簡潔程度與該功能的非慣用實現相比。 這是因為Counter對象有一個方便的most_common()方法,該方法可以為我們快速獲取所需的信息-最頻繁出現的項目及其相關計數。 實際上,為給我們更大的靈活性,我們可以選擇找出任意數量的最頻繁出現的項目,如下所示。

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.

請注意,當您未在most_common()方法中指定任何數字時,所有元素都將按照計數的降序作為列表返回。 降序可能非常有用,這使我們可以檢索數量最少的商品,如下所示。

Least Frequent Item
最少的頻繁項目

更新計數器對象 (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對象用于對列表中的元素進行計數。 但是,如果我們得到另一個列表并想要更新原始的Counter對象而不創建一個新的對象,該怎么辦?

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對象,實現映射協議,以便我們可以相應地更新每個鍵的值。 值得注意的是,如果鍵不存在于原始Counter對象中(與內置dict數據類型不同),則不會引發KeyValue異常,因為默認情況下, Counter對象中缺少的鍵的值為0 ,正如我們在訪問單個項目時看到的那樣。

Update Counter Object
更新計數器對象

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.

有一種更優雅的方式來更新原始的Counter對象-使用Counterupdate()方法。 不要將此update()方法與dict'update()方法混淆,后者會更新匹配鍵的值。 相反, Counterupdate()方法將在內部生成項目的計數,并使用這些計數來更新原始的Counter對象,如下面的代碼片段所示。

The update() Method
update()方法

數學運算 (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類的名稱是參考性的,它告訴您它對我們很重要。 如我們所見,我們可以使用update()方法更新計數。 更廣泛地說,當我們有多個Counter對象時,我們可以對其進行加減運算。 當我們添加Counter對象時,元素的計數將合并。

The following code shows you such operation, which should be self-explanatory:

下面的代碼向您展示了這樣的操作,這應該是不言而喻的:

Addition of Counter Objects
添加計數器對象

In a similar fashion, we can subtract one Counter object from another Counter object using the minus operator, as shown below.

以類似的方式,我們可以使用減號運算符從另一個Counter對象中減去一個Counter對象,如下所示。

Subtraction of Counter Objects
相減對象

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.

在上面的代碼中,需要注意的一件事是,當我們使用減法運算符時,所得的Counter對象將僅包括具有正計數的那些鍵值對。 此行為不同于Counter的方法subtract() ,該方法還將包括負數。 另外,如前所述,當Counter不包含元素時,默認情況下它們的計數為零。 牢記這兩點,讓我們看一下subtract()方法如何與Counter對象一起工作。

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對象包含多個帶有負計數的元素。 還要注意的另一件事是subtract()方法就地更改了計數,這意味著subtract()方法將返回None并且它會更改原始Counter對象的計數。

集樣操作 (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:

除了支持數學運算外, Counter對象還可以使用兩種類似集合的運算: unionintersection 。 要創建兩個Counter對象的“聯合”,只需使用OR運算符(即,豎線)將它們連接。 聯合操作將通過使用結果Counter對象中每個匹配鍵的最大計數來執行。 一個簡單的示例如下所示:

Union of Counters
柜臺聯盟

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.

要創建兩個Counter對象的“交集”,只需使用AND運算符(即&符號)將它們連接起來。 將通過使用結果Counter對象中每個匹配鍵的最小計數來執行相交操作。 一個簡單的例子如下所示。

Intersection of Counters
柜臺相交

其他功能亮點 (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:

在上一節中,我們了解了可以從可迭代對象(包括元組,列表和字符串)創建Counter對象。 如前所述, Counter類是內置dict類的子類,因此我們可以使用dict類可用的實例化方法。 下面顯示了一些示例,并附有解釋性注釋:

Construct Counters
建造柜臺

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:

我們已經看到, Counter對象的計數是從計數或數學運算得出的。 如果可以使用的話,我們可以直接設置特定元素的數量。 另外,我們可以從Counter對象中刪除元素,就像從dict對象中刪除鍵/值對一樣。 參見下面的用法:

Manipulate Counter Objects
操作計數器對象

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對象的另一個有用的方法是elements()方法,該方法創建所有項目的迭代器,每個項目都具有與其計數匹配的期望出現次數。 該方法對于迭代已知數字的不同項特別方便。

The elements() Method
elements()方法

結論 (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類,用于對序列中的可哈希對象進行計數,包括元組,列表和字符串。 作為dict數據類型的子類,我們可以像常規dict對象一樣,從序列以及映射和關鍵字參數中創建Counter對象。 Counter對象具有高度的靈活性,因為您可以根據需要操縱這些元素的計數。 您甚至可以更新,合并和相交Counter對象。

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()方法,該方法使我們可以用一行代碼找出最頻繁的項目。 也可以利用most_common()方法找出最不頻繁的項目,該方法以降序對項目進行排序,從而使我們能夠檢索最不常見項目的最后一個項目。

Thanks for reading.

謝謝閱讀。

翻譯自: https://medium.com/better-programming/count-items-in-python-with-the-help-of-counter-objects-c08d8d486e45

python對象引用計數器

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388015.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388015.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388015.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

套接字設置為(非)阻塞模式

當socket 進行TCP 連接的時候(也就是調用connect 時),一旦網絡不通,或者是ip 地址無效,就可能使整個線程阻塞。一般為30 秒(我測的是20 秒)。如果設置為非阻塞模式,能很好的解決這個…

經典問題之「分支預測」

問題 來源 &#xff1a;stackoverflow 為什么下面代碼排序后累加比不排序快&#xff1f; public static void main(String[] args) {// Generate dataint arraySize 32768;int data[] new int[arraySize];Random rnd new Random(0);for (int c 0; c < arraySize; c)data…

vi

vi filename :打開或新建文件&#xff0c;并將光標置于第一行首 vi n filename &#xff1a;打開文件&#xff0c;并將光標置于第n行首 vi filename &#xff1a;打開文件&#xff0c;并將光標置于最后一行首 vi /pattern filename&#xff1a;打開文件&#xff0c;并將光標置…

數字圖像處理 python_5使用Python處理數字的高級操作

數字圖像處理 pythonNumbers are everywhere in our daily life — there are phone numbers, dates of birth, ages, and other various identifiers (driver’s license and social security numbers, for example).電話號碼在我們的日常生活中無處不在-電話號碼&#xff0c;…

05精益敏捷項目管理——超越Scrum

00.我們不是不知道它會給我們帶來麻煩&#xff0c;只是沒想到麻煩會有這么多。——威爾.羅杰斯 01.知識點&#xff1a; a.Scrum是一個強大、特意設計的輕量級框架&#xff0c;器特性就是將軟件開發中在制品的數量限制在團隊層級&#xff0c;使團隊有能力與業務落班一起有效地開…

帶標題的圖片輪詢展示

為什么80%的碼農都做不了架構師&#xff1f;>>> <div> <table width"671" cellpadding"0" cellspacing"0"> <tr height"5"> <td style"back…

linux java 查找進程中的線程

這里對linux下、sun(oracle) JDK的線程資源占用問題的查找步驟做一個小結&#xff1b;linux環境下&#xff0c;當發現java進程占用CPU資源很高&#xff0c;且又要想更進一步查出哪一個java線程占用了CPU資源時&#xff0c;按照以下步驟進行查找&#xff1a;(一)&#xff1a;通過…

定位匹配 模板匹配 地圖_什么是地圖匹配?

定位匹配 模板匹配 地圖By Marie Douriez, James Murphy, Kerrick Staley瑪麗杜里茲(Marie Douriez)&#xff0c;詹姆斯墨菲(James Murphy)&#xff0c;凱里克史塔利(Kerrick Staley) When you request a ride, Lyft tries to match you with the driver most suited for your…

Sprint計劃列表

轉載于:https://www.cnblogs.com/zhs20160715/p/9953586.html

MySQL學習【第十二篇事務中的鎖與隔離級別】

一.事務中的鎖 1.啥是鎖&#xff1f; 顧名思義&#xff0c;鎖就是鎖定的意思 2.鎖的作用是什么&#xff1f; 在事務ACID的過程中&#xff0c;‘鎖’和‘隔離級別’一起來實現‘I’隔離性的作用 3.鎖的種類 共享鎖&#xff1a;保證在多事務工作期間&#xff0c;數據查詢不會被阻…

Android WebKit

這段時間基于項目需要 在開發中與WebView的接觸比較多&#xff0c;前段時間關于HTML5規范塵埃落定的消息出現在各大IT社區頭版上&#xff0c;更有人說&#xff1a;HTML5將顛覆原生App開發 雖然我不太認同這一點 但是關于HTML5JSCSSNative的跨平臺開發模式還是為很多企業節省了開…

jQuery的事件綁定和解綁

1、綁定事件 語法&#xff1a; bind(type,data,fn) 描述&#xff1a;為每一個匹配元素的特定事件&#xff08;像click&#xff09;綁定一個事件處理器函數。 參數解釋&#xff1a; type (String) : 事件類型 data (Object) : (可選) 作為event.data屬性值傳遞給事件對象的額外數…

軟件測試框架課程考試_那考試準備課程值得嗎?

軟件測試框架課程考試By Levi Petty李維佩蒂(Levi Petty) This project uses a public, synthesized exam scores dataset from Kaggle to analyze average scores in Math, Reading, and Writing subject areas, relative to the student’s parents’ level of education an…

開博第一天

開博第一天 紀念一下 轉載于:https://www.cnblogs.com/yang-9654/p/9959388.html

GitLab 11.9 正式發布,自動化工具 ChatOps 已開源

GitLab 11.9 已正式發布&#xff0c;該版本新增了兩個和安全相關的特性&#xff0c;一是快速檢查私密信息是否泄漏&#xff0c;從該版本起在 CI/CD 過程中會掃描開發者提交的信息是否包含私密內容&#xff0c;有的話會在合并 PR 時向開發者發送警報&#xff1b;二是改進了合并 …

DOCKER windows安裝

DOCKER windows安裝 DOCKER windows安裝 1.下載程序包2. 設置環境變量3. 啟動DOCKERT4. 分析start.sh5. 利用SSH工具管理6. 下載鏡像 6.1 下載地址6.2 用FTP工具上傳tar包6.3 安裝6.4 查看鏡像6.5 運行 windows必須是64位的 1.下載程序包 安裝包 https://github.com/boot2doc…

為什么在Python代碼中需要裝飾器

Python is praised for its clarity and syntactic sugariness. In this article, I will teach you to use decorators in Python to make your code readable and clean.Python的清晰性和語法含糖度受到贊譽。 在本文中&#xff0c;我將教您在Python中使用裝飾器&#xff0c;…

Elasticsearch Reference [6.7] ? Modules ? Network Settings

2019獨角獸企業重金招聘Python工程師標準>>> Search Settings Node Network Settingsedit Elasticsearch binds to localhost only by default. This is sufficient for you to run a local development server (or even a development cluster, if you star…

【百度】大型網站的HTTPS實踐(一)——HTTPS協議和原理

大型網站的HTTPS實踐&#xff08;一&#xff09;——HTTPS協議和原理 原創 網絡通信/物聯網 作者&#xff1a;AIOps智能運維 時間&#xff1a;2018-11-09 15:07:39 349 0前言 百度于2015年上線了全站HTTPS的安全搜索&#xff0c;默認會將HTTP請求跳轉成HTTPS。從今天開始&…

數據清理最終實現了自動化

蘋果 | GOOGLE | 現貨 | 其他 (APPLE | GOOGLE | SPOTIFY | OTHERS) Editor’s note: The Towards Data Science podcast’s “Climbing the Data Science Ladder” series is hosted by Jeremie Harris. Jeremie helps run a data science mentorship startup called Sharpest…