博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python之collections之counter
阅读量:5122 次
发布时间:2019-06-13

本文共 4889 字,大约阅读时间需要 16 分钟。

一、定义

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:

 

def copy(self):     'Return a shallow copy.'     return self.__class__(self)   Counter的浅拷贝

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

你可能感兴趣的文章
集合体系
查看>>
vi命令提示:Terminal too wide
查看>>
引用 移植Linux到s3c2410上
查看>>
MySQL5.7开多实例指导
查看>>
[51nod] 1199 Money out of Thin Air #线段树+DFS序
查看>>
poj1201 查分约束系统
查看>>
Red and Black(poj-1979)
查看>>
分布式锁的思路以及实现分析
查看>>
腾讯元对象存储之文件删除
查看>>
jdk环境变量配置
查看>>
安装 Express
查看>>
包含列的索引:SQL Server索引的阶梯级别5
查看>>
myeclipse插件安装
查看>>
浙江省第十二届省赛 Beauty of Array(思维题)
查看>>
NOIP2013 提高组 Day1
查看>>
cocos2dx 3.x simpleAudioEngine 长音效被众多短音效打断问题
查看>>
存储(硬件方面的一些基本术语)
查看>>
观察者模式
查看>>
Weka中数据挖掘与机器学习系列之基本概念(三)
查看>>
Win磁盘MBR转换为GUID
查看>>