python之collections之counter

1. 在 SAP ABAP 事物码 SEGW 里创建 SAP OData 项目 本文介绍如何在 SAP ABAP 事物码 SEGW 里创建 SEGW 项目,使用工具生成 Runtime 运行时需要的资源。 阅读详情

 

转自https://www.cnblogs.com/baotouzhangce/p/6179911.html

一、定义

Counter(计数器)是对字典的补充,用于追踪值的出现次数。

Counter是一个继承了字典的类(Counter(dict))

二、相关方法

继承了字典的类,有关字典的相关方法也一并继承过来。

比如items()方法

 

def most_common(self, n=None):
    '''List the n most common elements and their counts from the most
    common to the least.  If n is None, then list all element counts.

    >>> Counter('abcdeabcdabcaba').most_common(3)
    [('a', 5), ('b', 4), ('c', 3)]
  截取指定位数的值
    '''
    # Emulate Bag.sortedByCount from Smalltalk
    if n is None:
        return sorted(self.items(), key=_itemgetter(1), reverse=True)
    return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
eg:

 

def elements(self):
    '''
  显示计数器中所有的元素
  Iterator over elements repeating each as many times as its count.

    >>> c = Counter('ABCABC')
    >>> sorted(c.elements())
    ['A', 'A', 'B', 'B', 'C', 'C']

    # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
    >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
    >>> product = 1
    >>> for factor in prime_factors.elements():     # loop over factors
    ...     product *= factor                       # and multiply them
    >>> product
    1836

    Note, if an element's count has been set to zero or is a negative
    number, elements() will ignore it.

    '''
    # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
    return _chain.from_iterable(_starmap(_repeat, self.items()))

# Override dict methods where necessary
eg:

 

@classmethod
def fromkeys(cls, iterable, v=None):
    # There is no equivalent method for counters because setting v=1
    # means that no element can have a count greater than one.
    此功能没有实现
    raise NotImplementedError(
        'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

def update(*args, **kwds):
    '''
  更新Counter,对于已有的元素计数加一,对没有的元素进行添加
  Like dict.update() but add counts instead of replacing them.

    Source can be an iterable, a dictionary, or another Counter instance.

    >>> c = Counter('which')
    >>> c.update('witch')           # add elements from another iterable
    >>> d = Counter('watch')
    >>> c.update(d)                 # add elements from another counter
    >>> c['h']                      # four 'h' in which, witch, and watch
    4

    '''
    # The regular dict.update() operation makes no sense here because the
    # replace behavior results in the some of original untouched counts
    # being mixed-in with all of the other counts for a mismash that
    # doesn't have a straight-forward interpretation in most counting
    # contexts.  Instead, we implement straight-addition.  Both the inputs
    # and outputs are allowed to contain zero and negative counts.

    if not args:
        raise TypeError("descriptor 'update' of 'Counter' object "
                        "needs an argument")
    self, *args = args
    if len(args) > 1:
        raise TypeError('expected at most 1 arguments, got %d' % len(args))
    iterable = args[0] if args else None
    if iterable is not None:
        if isinstance(iterable, Mapping):
            if self:
                self_get = self.get
                for elem, count in iterable.items():
                    self[elem] = count + self_get(elem, 0)
            else:
                super(Counter, self).update(iterable) # fast path when counter is empty
        else:
            _count_elements(self, iterable)
    if kwds:
        self.update(kwds)
eg:

 

 

def subtract(*args, **kwds):
    '''Like dict.update() but subtracts counts instead of replacing them.
    Counts can be reduced below zero.  Both the inputs and outputs are
    allowed to contain zero and negative counts.

    Source can be an iterable, a dictionary, or another Counter instance.

    >>> c = Counter('which')
    >>> c.subtract('witch')             # subtract elements from another iterable
    >>> c.subtract(Counter('watch'))    # subtract elements from another counter
    >>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
    0
    >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
    -1
  对指定的Counter元素做减法运算,对出现过的累计减一(可以出现负数),对没有出现过的进行0-1运算
    '''
    if not args:
        raise TypeError("descriptor 'subtract' of 'Counter' object "
                        "needs an argument")
    self, *args = args
    if len(args) > 1:
        raise TypeError('expected at most 1 arguments, got %d' % len(args))
    iterable = args[0] if args else None
    if iterable is not None:
        self_get = self.get
        if isinstance(iterable, Mapping):
            for elem, count in iterable.items():
                self[elem] = self_get(elem, 0) - count
        else:
            for elem in iterable:
                self[elem] = self_get(elem, 0) - 1
    if kwds:
        self.subtract(kwds)
eg:

返回列表中出现次数最多的元素及其次数

返回多个最多

数学运算

  1. >>> c = Counter(a=3, b=1)

  2. >>> d = Counter(a=1, b=2)

  3. >>> c + d # add two counters together: c[x] + d[x]

  4. Counter({'a': 4, 'b': 3})

  5. >>> c - d # subtract (keeping only positive counts)

  6. Counter({'a': 2})

  7. >>> c & d # intersection: min(c[x], d[x])

  8. Counter({'a': 1, 'b': 1})

  9. >>> c | d # union: max(c[x], d[x])

  10. Counter({'a': 3, 'b': 2})

 

GD32F4xx MCU ADC+DMA 多通道采样 1、GD32F4xx ADC GD32F4xx 的12位ADC是一种采用逐次逼近方式的模拟数字转换器。 1.1 主要特征 可配置12位、10位、8位、6位分辨率; ADC采样率:12位分辨率为2.6MSPs,10位分辨率为3.0 MSPs。分辨率越低,转换越快; PS: MSPs (模拟混合信号转换速率),是指完成1次从模拟转换到数字的AD转换所需的时间的倒数。常用单位是ksps和Msps,表示每秒采样(千)/(百万)次(kilo / Million Samples per Second)。 1msps 阅读详情

相关推荐

Windows安装ros2(Jazzy版本+win10/win11)-1.配置windows终端

更高版本的terminal可能设置里更加丰富, 有默认以管理员身份启动的选项等,可自行配置。打开微软应用商店, 在其中搜索并下载 Terminal 即可(注意别挂梯子)下载并安装, 安装的位置自行替换,建议别放到系统盘中。点击任务栏中的搜索, 输入store。

weixin_48398592的博客 1452

python 将counter 的结果转换为字典

有时候有这种需要,比如我对一个文本计数了,然后想做词云图。 这时候可以用 直接使用dict就可以。 all_words = sum(corpus2, []) len(all_words) c = Counter(all_words) dict(c.most_common(10)) #直接使用dict wc = WordCloud().generate_from_frequencies(dict(c.most_common(200))) plt.imshow(wc) 这也可以认为,dict功

weixin_40340586的博客 3864

图像调整亮度饱和度 c语言,【C#/WPF】调节图像的HSL(色相、饱和度、明亮度)...

先说概念:HSL是一种描述颜色的方式(其他颜色描述方式还有大家熟悉的RGB值)。HSL三个字母分别表示图像的Hue色相、Saturation饱和度、Lightness明亮度。需求:制作一个面板,包含三个滑动条,拖动滑动条可以修改目标图片的HSL值。即模仿PS中类似的功能,如下图:方案一:遍历所有像素点,修改每个点的HSL值。前台界面:一个Image控件显示目标图片,一个Button按钮点击一下降低...

weixin_39935777的博客 1154

python计数器—collections.Counter

Counter计数器,最主要的作用是计算“可迭代序列”中各个元素(element)的数量。具体用法如下: 使用前导入: from collections import Counter 1.统计“可迭代序列”中每个元素出现的次数 对列表/字符串作用 #对列表作用 list=[1,2,2,2,3,6,6,6,6] print(Counter(list)) #Counter({6: 4, 2: 3, 1: 1, 3: 1}) #对字符串作用 temp=Counter('aabbcdeffgg

Judy18的博客 7259

PX4飞控 vs 大疆A3:开源与闭源方案在无人机硬件架构中的实战对比

本文深入对比了PX4飞控与大疆A3在无人机硬件架构上的差异,分析了开源与闭源方案在工业级无人机开发中的优劣势。通过详细的硬件配置、传感器兼容性、扩展能力及性能测试数据,为开发者提供选型指南,特别适合需要自定义算法和复杂功能集成的项目。

a3b4c5的博客 886

Unity特效序列帧输出全攻略:Recorder+Timeline保姆级教程(解决透明通道问题)

本文提供Unity特效序列帧输出的完整解决方案,重点讲解如何结合Recorder与Timeline工具,实现带透明通道的PNG序列帧高效输出。通过保姆级教程,详细解析摄像机隔离、层级设置、参数配置等关键步骤,并深度解决透明通道丢失等常见问题,帮助特效师和动画师打通引擎创作与后期合成的工作流。

tensorflowjs6的博客 429

python counter_Python Counter() 的实现

collections.Counter 源码实现Counter 的相关源码在lib下的collections.py里,本文所提及的源码是python2.7版本, 可参见github。__init__class Counter(dict):'''Dict subclass for counting hashable items. Sometimes called a bagor multiset....

weixin_39959369的博客 241

VC Spyglass实战指南:从零开始掌握CDC约束配置与调试

本文详细介绍了如何使用VC Spyglass进行CDC约束配置与调试,从基础环境搭建到典型CDC问题调试实战,帮助开发者快速掌握跨时钟域验证技术。通过TCL脚本和SDC约束的深度解析,提升CDC验证效率,避免常见设计风险。

weixin_26757925的博客 294

python counter转dict,如何将Counter对象转换为dict?

Data frame:pair = collections.defaultdict(collections.Counter)e.g.pair = {'doc1': {'word1':4, 'word2':3},'doc2': {'word1':2, 'word3':4},'doc3': {'word2':2, 'word4':1},...}I want to keep the data fr...

weixin_39823200的博客 1775

王者荣耀AI绝悟如何选英雄?

王者荣耀AI绝悟如何选英雄? 【抢射手?抢中单位?「绝悟」在打王者荣耀时是如何选英雄的?】 腾讯 AI Lab 开发的 AI 智能体「绝悟」已让王者峡谷不再只是人类召唤师的竞技场,而且这个 AI 战队在上月底进化成了「完全体」。在一局完整的比赛中,英雄选择阶段是至关重要的(比如五射手或五法师阵容会有官方劝退)。 近日,腾讯 AI Lab 和上海交通大学发布的一篇论文介绍了绝悟的英雄选择策略:Ju...

不断学习,不断进步,提高自己 1万+

Android Camera MTK框架

Camera简介: 虽然前文说道Android在5.0之后就推出了Camera2 API,但是各个厂家的基本未适配,导致目前市场上大部分机型使用的仍然是Camera1 API。PS:Android 9.0 Google强制要求各个平台厂商(高通/MTK/华为等)支持Camera2,不再兼容Camera1。 ...

weixin_49303682的博客 5506

python中collections中的Counter解析

collections — High-performance container datatypes 在2.4版本中新加入,源代码Lib/collections.py和Lib/_abcoll.py。该模块实现了专用的容器数据类型来替代python的通用内置容器:dict(字典),list(列表), set(集合)和tuple(元组)。 除了具体的容器类,collections模块还提供了abst...

光英的记忆博客 1万+

第二节:Vben Admin 登录逻辑梳理和对接后端准备

第一节,我们已经配置了前端环境,运行起来了我们的Vben Admin的项目。本节内容,我们先熟悉下项目的目录和文件,然后开始准备对接后端程序路由在 src/router页面在 sr/views本节前端登录逻辑梳理完成了,后端只要在/api/login 接口编写返回逻辑,前后段就可以打通了,具体详情我们下一节介绍。

cuiwin的专栏 5084

Python collections.Counter()用法

Python collections.Counter用法什么是collectionsCounterCounter操作例子 什么是collections collections在python官方文档中的解释是High-performance container datatypes,直接的中文翻译解释高性能容量数据类型。 它总共包含五种数据类型: 其中Counter中文意思是计数器,也就是我们常用于...

qwe1257的博客 16万+

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Python的collections.Counter类型,师兄教你如何去掌握python的collections.Counter类型,熟练运用python collections.Counter类型。

collections.Counter 类型可以用来给可散列的对象计数,或者是当成多重集合来使用 —— 多重集合就是在集合里的元素可以多次出现。collections.Counter 类型其它编程语言中的 bags 或者 multisets2有相似之处。

kelai_6792的博客 1030

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Python collections模块之Counter()详解

Python collections模块之Counter详解Counter()most_common()elements()update()subtract() collections模块 ==> Python标准库,数据结构常用的模块;collections包含了一些特殊的容器,针对Python内置的容器,例如list、dict、set和tuple,提供了另一种选择。 collections模块常用类型有: 计数器(Counter) dict的子类,计算可hash的对象 双向队列(deq

chl183的博客 7万+

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

python3 collections.Counter

python collection.Counter用法介绍

zagky的博客 1366

python学习:collections.Counter用法

Python collections.Counter用法 什么是collections Counter Counter操作 例子 什么是collections collections在python官方文档中的解释是High-performance container datatypes,直接的中文翻译解释高性能容量数据类型。 它总共包含五种数据类型: 其中Counter中文意思是计数器,也就是我们常用于统计的一种数据类型,在使用Counter之后可以让我们的代码更加简单易读。 Counter

子非鱼的博客 696

python的collections.Counter方法

哈希表在python中可以用collections.Counter计数来体现。 该方法用于统计某序列中每个元素出现的次数,以键值对的方式存在字典中。但类型其实是Counter。 nums = [1, 2, 3, 1, 2, 1] counts = collections.Counter(nums) print(counts) ## Counter({1: 3, 2: 2, 3: 1}) 凭借这个结构,可以计算出某个序列中出现次数最多的某个元素。也即在得到了counts之后求max即可。但这个max需要给依

m0_47105444的博客 1万+

Python中的collections.Counter模块

1.collections模块介绍: collections是Python内建的一个集合模块,提供了许多有用的集合类。该模块实现了专门的容器数据类型,提供了Python的通用内置容器,dict,list,set和tuple的替代方法。 2.counter类 官网参考:https://docs.python.org/3.6/library/collections.html#collections.C...

chen_mushi的博客 1631

【Python】详解 collections.Counter

Counter,顾名思义是一个计数器。Counter 类作为一个无序的容器类型,以字典的 key-value 对形式存储元素,旨在统计各元素 (哈希项) 出现的次数。具体而言,key 表示元素,value 表示各元素 key 出现的次数,可为任意整数 (即包括0与负数)。Counter 类有时被称为bags 或 multisets 。我们在 IDLE 通过 help(collections.Counter) 可查看帮助文档。

闻韶 3290

Python collections.Counter

python collections.Counter 文章目录python collections.Counter1. 简介2. 初始化3. 取值和修改值4. 迭代5. 特殊方法5.1 `elements()`5.2 `most_common([n])`5.3 `total()`5.4 `subtract()`6. 集合特性 1. 简介 Counter 计数器,顾名思义就是用来计数的,最主要的作用就是计算“可迭代序列中”各个元素(element)的数量。 一个 Counter 是一个 dict 的子类,用

Teolih的博客 985

python counter_教你Python的collections.Counter类型

collections.Counter 类型可以用来给可散列的对象计数,或者是当成多重集合来使用 —— 多重集合就是集合里的元素可以出现多次1。collections.Counter 类型类似于其它编程语言中的 bags 或者 multisets2。(1)基本用法counter = collections.Counter(['生物', '印记', '考古学家', '生物', '枣', '印记'])...

weixin_39517868的博客 163

python的collections.Counter的简介

模块中的一个类,用于统计元素出现次数。它提供了一种简单高效的方式来统计列表、字符串或其他可迭代对象中每个元素的出现次数。是一个字典的子类,专门用于计数。它接受一个可迭代对象(如列表、字符串等)作为输入,并返回一个字典,其中键是元素,值是该元素出现的次数。方法返回一个列表,包含出现次数最多的前 n 个元素及其出现次数。对象支持一些基本的数学运算操作,如加法、减法、交集和并集。方法返回一个迭代器,按元素出现次数的顺序生成元素。的基本概念、常见用法和一些实用的代码示例。是 Python 标准库。

licy__的博客 1095

python collections_6. python Collections -- Counter

提供计数器工具以支持方便快捷的计数。 例如:语法:classcollections.Counter([iterable-or-mapping])Counter是用于计算可哈希对象的字典子类。它是一个无序的集合,其中元素以字典键的形式存储,并将其计数存储为字典值。计数允许为包括零或负计数的任何整数值。Counter类与其他语言的bag或multisets类似。元素从一个迭代中计数或从另一个映射(或计...

weixin_42619061的博客 182

如何使用 Python collections 模块中的 Counter 数据结构

在 Python 中,`collections` 模块提供了多种有用的工具来处理常见的任务,而 `Counter` 是其中一个非常强大且广泛应用的数据结构。`Counter` 是一个专门用于计数(统计)元素出现次数的容器,基于字典(`dict`)实现,能够轻松地进行元素计数、频率统计等操作。本文将深入介绍如何使用 `Counter`,并展示它在实际开发中的应用。

1973
上一篇: 初识机器学习——吴恩达《Machine Learning》学习笔记(二)
下一篇: python enumerate用法总结
Ta来自江湖
博客等级 码龄9年 24粉丝 31原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值