博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
collections系列
阅读量:4641 次
发布时间:2019-06-09

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

class Counter(dict):   Counter类继承dict类、继承了dict的所有功能 计数器:
例: import collectionsobj = collections.Counter('sdkasdioasdjoasjdoasd')print(obj) 得: Counter({'s': 5, 'd': 5, 'a': 4, 'o': 3, 'j': 2, 'k': 1, 'i': 1})

 

 
拿到前几位:
""" 数量大于等n的所有元素和计数器 """
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))
例: import collectionsobj = collections.Counter('sdkasdioasdjoasjdoasd') #elements  =>> 原生的值 #obj    =>> 处理完的数据print(obj)ret = obj.most_common(4)print(ret) 得:

Counter({'d': 5, 's': 5, 'a': 4, 'o': 3, 'j': 2, 'k': 1, 'i': 1})

[('d', 5), ('s', 5), ('a', 4), ('o', 3)]

 

 
打印所有的元素、没有个数 for item in obj.elements():    print(item)

 

dict otems()  keys()  values() couter(dic)#继承了所有字典的方法
otems()  keys()  values() “r”:3 elements()#所有的元素
for k,v in obj.items():    print(k,v)

 

 
import collections#obj = collections.Counter('sjhdaosdijoasjdoasd')obj = collections.Counter(['11','22','33','22'])print(obj)ret = obj.most_common(4)print(ret) 得:

Counter({'22': 2, '11': 1, '33': 1})

[('22', 2), ('11', 1), ('33', 1)]

 

 
def update(*args, **kwds): 更新计数器,其实就是增加;如果原来没有,则新建,如果有则加一        '''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)
 
例(增加): import collectionsobj = collections.Counter(['11','22','33','22'])print(obj)obj.update(['eric','11','11'])#增加print(obj) 得:

Counter({'22': 2, '11': 1, '33': 1})

Counter({'11': 3, '22': 2, '33': 1, 'eric': 1})

 

 
例(减去): import collectionsobj = collections.Counter(['11','22','33','22'])print(obj)obj.subtract(['eric','11','11'])#删除print(obj) 得:

Counter({'22': 2, '11': 1, '33': 1})

Counter({'22': 2, '33': 1, '11': -1, 'eric': -1})

 

 

 

转载于:https://www.cnblogs.com/mrzuo/p/7094911.html

你可能感兴趣的文章
IntelliJ idea学习资源
查看>>
Django Rest Framework -解析器
查看>>
ExtJs 分组表格控件----监听
查看>>
Hibernate二级缓存配置
查看>>
LoadRunner常用术语
查看>>
关于jedis2.4以上版本的连接池配置,及工具类
查看>>
记忆讲师石伟华微信公众号2017所有文章汇总(待更新)
查看>>
mechanize (1)
查看>>
FactoryBean
查看>>
Coolite动态加载CheckboxGroup,无法在后台中获取
查看>>
如何在我们项目中利用开源的图表(js chart)
查看>>
nfs服务器工作原理
查看>>
C3P0连接池工具类使用
查看>>
SVN常用命令备注
查看>>
孩子教育
查看>>
解决Cacti监控图像断断续续问题
查看>>
结构体的传参理解成员的存储方式
查看>>
python 进程与线程(理论部分)
查看>>
什么是API
查看>>
Java反射中method.isBridge() 桥接方法
查看>>