zoukankan      html  css  js  c++  java
  • [PY3]——找出一个序列中出现次数最多的元素/collections.Counter 类的用法

    问题

    怎样找出一个序列中出现次数最多的元素呢?

    解决方案

    collections.Counter 类就是专门为这类问题而设计的, 它甚至有一个有用的 most_common() 方法直接给了你答案

    collections.Counter 类

    1. most_common(n)统计top_n

    from collections import Counter
    words = [
        'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
        'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
        'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
        'my', 'eyes', "you're", 'under'
    ]
    #创建Counter对象
    word_counts=Counter(words)
    
    #most_common(n)函数可直接统计top-n
    top_three=word_counts.most_common(3)
    
    print(type(top_three))
    <class 'list'>
    
    print(top_three)
    [('eyes', 8), ('the', 5), ('look', 4)]

     

    2. 统计任意元素出现的次数

    Counter 对象可以接受任意的由可哈希(hashable)元素构成的序列对象

    在底层实现上,一个 Counter 对象就是一个字典,将元素映射到它出现的次数上

    print(word_counts['look'])
    4
    print(word_counts["you're"])
    1

     

    3. 两个Counter对象之间可以互相使用数学运算符,从而叠加/叠减统计

    word1 = [
        'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
        'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
        'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
        'my', 'eyes', "you're", 'under'
    ]
    word2 = ['why','are','you','not','looking','in','my','eyes']
    
    a=Counter(word1)
    b=Counter(word2)
    print(a)
    Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, 'not': 1, 'under': 1, "you're": 1, "don't": 1})
    
    print(b)
    Counter({'eyes': 1, 'not': 1, 'are': 1, 'you': 1, 'in': 1, 'why': 1, 'my': 1, 'looking': 1})
    
    print(a+b)
    Counter({'eyes': 9, 'the': 5, 'my': 4, 'look': 4, 'into': 3, 'around': 2, 'not': 2, 'under': 1, 'looking': 1, 'you': 1, 'why': 1, 'in': 1, 'are': 1, "you're": 1, "don't": 1})
    
    print(a-b)
    Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'around': 2, 'my': 2, 'under': 1, "you're": 1, "don't": 1})
  • 相关阅读:
    windows7 下 apache2.4 和 php5.5 及 mysql5.6 的安装与配置
    JavaScript高级编程 (1)
    关于解决乱码问题的一点探索之二(涉及Unicode(utf-16)和GBK)
    关于解决乱码问题的一点探索之一(涉及utf-8和GBK)
    Windows上安装、配置MySQL的常见问题
    解析DXF图形文件格式
    vue三十一:vue配置反向代理
    vue三十:eslint修复错误和打包用于生产
    vue二十九:多个文件组件集成
    vue二十八:Vue-Cli之环境搭建之node安装脚手架和使用脚手架创建vue项目
  • 原文地址:https://www.cnblogs.com/snsdzjlz320/p/7194150.html
Copyright © 2011-2022 走看看