• collections.Counter用法


    Counter中文意思是计数器,也就是我们常用于统计的一种数据类型,在使用Counter之后可以让我们的代码更加简单易读。

    我们先看一个简单的例子:

    #统计词频
    colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
    result = {}
    for color in colors:
        if result.get(color)==None:
            result[color]=1
        else:
            result[color]+=1
    print (result)
    #{'red': 2, 'blue': 3, 'green': 1}
    

    1.下面我们看用Counter怎么实现:

    from collections import Counter
    colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
    c = Counter(colors)
    
    print(c)
    #Counter({'blue': 3, 'green': 1, 'red': 2})
    
    print (dict(c))
    #{'red': 2, 'blue': 3, 'green': 1}
    

    2.创建Counter的时候传进去一个迭代器(数组,字符串,字典等):

    c = Counter('gallahad')                 # 传进字符串
    print(c)
    #Counter({'a': 3, 'd': 1, 'g': 1, 'h': 1, 'l': 2})
    
    c = Counter({'red': 4, 'blue': 2})      # 传进字典
    print(c)
    #Counter({'blue': 2, 'red': 4})
    
    c = Counter(cats=4, dogs=8)             # 传进元组
    print(c)
    #Counter({'cats': 4, 'dogs': 8})
    

    3.判断是否包含某元素,可以转化为dict然后通过dict判断,Counter也带有函数可以判断:

    c = Counter(['eggs', 'ham'])
    print(c)
    #Counter({'eggs': 1, 'ham': 1})
    
    c['bacon']                              # 不存在就返回0
    #0
    

    4.删除元素:

    c['sausage'] = 0                        # counter entry with a zero count
    del c['sausage']   
    

    5.获得所有元素:

    c = Counter(a=4, b=2, c=0, d=-2)
    print(c)
    #Counter({'a': 4, 'b': 2, 'c': 0, 'd': -2})
    
    list(c.elements())
    #['a', 'a', 'a', 'a', 'b', 'b']
    

    6.查看最常见出现的k个元素:

    Counter('abracadabra').most_common(3)
    #[('a', 5), ('r', 2), ('b', 2)]
    

    7.Counter更新:

    c = Counter(a=3, b=1)
    d = Counter(a=1, b=2)
    c + d                       # 相加
    #Counter({'a': 4, 'b': 3})
    c - d                       # 相减,如果小于等于0,删去
    #Counter({'a': 2})
    c & d                       # 求最小
    #Counter({'a': 1, 'b': 1})
    c | d                       # 求最大
    #Counter({'a': 3, 'b': 2})

    实战:给定一个非空的整数数组,返回其中出现频率前 高的元素。如输入: nums = [1,1,1,2,2,3], k = 2      输出: [1,2]

    from collections import Counter
    class Solution:
        def topKFrequent(self, nums: List[int], k: int) -> List[int]:
            return [i[0] for i in Counter(nums).most_common(k)]
    #most_common(k)是Counter的一个函数 #这个函数就是返回最多出现的K项,但是返回的形式是一个元祖列表,

     

    原文链接:https://blog.csdn.net/qwe1257/article/details/83272340

  • 相关阅读:
    C++指针笔记
    破解入门【OllyDebug爆破程序】
    c++类的定义《一》
    数组
    while循环语句的使用
    MS10-046漏洞测试
    For循环语句的使用
    C++Builder编写计算器
    C++自定义函数
    SQLyog简介
  • 原文地址:https://www.cnblogs.com/USTC-ZCC/p/12884226.html
Copyright © 2020-2023  润新知