官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 玛多县| 吉隆县| 武乡县| 克山县| 娄烦县| 高青县| 崇信县| 偏关县| 宜州市| 格尔木市| 巴林左旗| 新建县| 蒙山县| 康乐县| 离岛区| 库伦旗| 罗山县| 谷城县| 抚州市| 新余市| 普陀区| 平湖市| 祁连县| 盘山县| 张家口市| 承德县| 响水县| 阿勒泰市| 罗城| 祁连县| 连江县| 永和县| 买车| 利津县| 泽州县| 连平县| 湘乡市| 酒泉市| 莱芜市| 昭苏县| 安乡县|