• [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})
  • 相关阅读:
    动态代理,反射的用途及实现
    谈一谈web.xml中的context-param和init-param
    后端程序员需要了解的前端知识(持续更新中)
    angularJS要点记录,$location,$http等等
    HTTP1.0和HTTP2.0的区别,以及HTTP和HTTPS的区别
    浅谈Fork/Join框架
    ConcurrentHashMap 的工作原理及源码分析,如何统计所有的元素个数
    HTTP协议常见的状态码
    图解HTTP,状态码,TCP、UDP等网络协议相关总结(持续更新)
    jmeter(五)JDBC Request
  • 原文地址:https://www.cnblogs.com/snsdzjlz320/p/7194150.html
Copyright © 2020-2023  润新知