• collections系列


    class Counter(dict):
      Counter类继承dict类、继承了dict的所有功能

    计数器:
    例:
    import
    collections obj = 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
    collections obj = 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
    collections obj = 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
    collections obj = 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})

    
    
    


  • 相关阅读:
    shell脚本,批量创建10个系统帐号并设置密码为随机8位字符串。
    shell脚本,在指定目录下通过随机小写10个字母加固定字符串oldboy批量创建10个html文件。
    shell脚本,按字母出现频率降序排序。
    django 上传图片、使用PIL制作缩略图并保存到sea的storage
    mongo数据库基本操作--python篇
    看懂sh脚本
    推荐系统实践--基于用户的协同过滤算法
    推荐系统实践--概述
    django “如何”系列10:如何管理静态文件
    django “如何”系列9:三合一:利用遗留的数据库、输出csv和输出pdf
  • 原文地址:https://www.cnblogs.com/mrzuo/p/7094911.html
Copyright © 2020-2023  润新知