- Python Data Structures and Algorithms
- Benjamin Baka
- 256字
- 2021-07-09 19:45:05
Counter objects
Counter is a subclass of a dictionary where each dictionary key is a hashable object and the associated value is an integer count of that object. There are three ways to initialize a counter. We can pass it any sequence object, a dictionary of key:value pairs, or a tuple of the format (object = value, ...), for example:

We can also create an empty counter object and populate it by passing its update method an iterable or a dictionary, for example:

Notice how the update method adds the counts rather than replacing them with new values. Once the counter is populated, we can access stored values in the same way we would for dictionaries, for example:

The most notable difference between counter objects and dictionaries is that counter objects return a zero count for missing items rather than raising a key error, for example:

We can create an iterator out of a Counter object by using its elements() method. This returns an iterator where counts below one are not included and the order is not guaranteed. In the following code, we perform some updates, create an iterator from Counter elements, and use sorted() to sort the keys alphabetically:

Two other Counter methods worth mentioning are most_common() and subtract(). The most common method takes a positive integer argument that determines the number of most common elements to return. Elements are returned as a list of (key ,value) tuples. The subtract method works exactly like update except instead of adding values, it subtracts them, for example:

- C++面向對象程序設計(第三版)
- Oracle Exadata性能優化
- Python 深度學習
- Visual Basic程序設計(第3版):學習指導與練習
- 區塊鏈:以太坊DApp開發實戰
- Python:Master the Art of Design Patterns
- Visual C#.NET程序設計
- 低代碼平臺開發實踐:基于React
- PLC應用技術(三菱FX2N系列)
- 第一行代碼 C語言(視頻講解版)
- Visual Basic程序設計習題與上機實踐
- Spring技術內幕:深入解析Spring架構與設計原理(第2版)
- 分布式數據庫原理、架構與實踐
- JavaScript悟道
- Improving your Penetration Testing Skills