• Python中对序列数据的汇总(collections模块)


    目录

    Counter

    most_common 


    对于序列如字符串str、列表list和tuple可以统计里面数据出现的次数。我们使用的是 collections 模块。

    collections模块的常用方法有:

    • 计数器(Counter)
    • 双向队列(deque)
    • 默认字典(defaultdict)
    • 有序字典(OrderedDict)
    • 可命名元组(namedtuple)

    使用以上类型时需要导入模块 from collections import *

    Counter

    Counter()方法对传入的序列中出现的数据进行汇总,返回一个<class 'collections.Counter'>的对象

    from collections import Counter
    a="aabcac"
    b=['a','a','b','c','a','c']
    c=('a','a','b','c','a','c')
    print(Counter(a),type(Counter(a)))
    print(Counter(b))
    print(Counter(c))
    #######################################
    Counter({'a': 3, 'c': 2, 'b': 1}) <class 'collections.Counter'>
    Counter({'a': 3, 'c': 2, 'b': 1})
    Counter({'a': 3, 'c': 2, 'b': 1})

    most_common 

    most_common方法对Counter()汇总的数据进行从高到低的排序,返回前 n 个元素的字典,返回的是列表型的数据

    from collections import Counter
    a="aabcac"
    b=['a','a','b','c','a','c']
    c=('a','a','b','c','a','c')
    print(Counter(a))
    print(Counter(b))
    print(Counter(c))
    
    print(Counter(a).most_common(3),type(Counter(a).most_common(3)))
    print(Counter(b).most_common(2))
    print(Counter(c).most_common(1))
    ##############################################
    Counter({'a': 3, 'c': 2, 'b': 1})
    Counter({'a': 3, 'c': 2, 'b': 1})
    Counter({'a': 3, 'c': 2, 'b': 1})
    [('a', 3), ('c', 2), ('b', 1)] <class 'list'>
    [('a', 3), ('c', 2)]
    [('a', 3)]
  • 相关阅读:
    Opencv中cvCopy()和cvCloneImage()的区别(转)
    什么是DC?
    UpdateDate()函数的作用
    宏定义函数指针类型【转】
    将openCV中的IplImage格式的图片显示到Picture控件上
    C程序调用shell脚本共有三种方法
    memset ,memcpy ,memmove,strcpy 的根本区别 与实现
    sizeof strlen length()
    itoa 实现
    string 与 char * 转换
  • 原文地址:https://www.cnblogs.com/csnd/p/11807836.html
Copyright © 2020-2023  润新知