美文网首页
用Counter进行计数统计

用Counter进行计数统计

作者: 叶田的学习笔记 | 来源:发表于2018-11-05 18:36 被阅读0次

    统计某一项出现的次数。

    from collections import Counter
    
    some_data = ['a','s',2,'a','b','b','a']
    print(Counter(some_data))
    
    # 用elements()方法来获取Counter中的key值
    print(list(Counter(some_data).elements()))
    
    # 利用most_common()可以找出前N个出现频率最高的元素及它们对应的次数
    print(Counter(some_data).most_common(2))
    
    # 当访问不存在的元素时,默认返回0而不是抛出KeyError异常
    print(Counter(some_data)['c'])
    
    结果:
    Counter({'a': 3, 'b': 2, 's': 1, 2: 1})
    ['a', 'a', 'a', 's', 2, 'b', 'b']
    [('a', 3), ('b', 2)]
    0
    

    官方文档说明:https://docs.python.org/3.6/library/collections.html?highlight=counter#collections.Counter

    相关文章

      网友评论

          本文标题:用Counter进行计数统计

          本文链接:https://www.haomeiwen.com/subject/gotexqtx.html