zoukankan      html  css  js  c++  java
  • 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)]
  • 相关阅读:
    percona_xtrabackup
    利用java实现的一个发送手机短信的小例子
    使用mybatis执行oracle存储过程
    oracle 存储过程 基础
    oracle存储过程常用技巧
    oracle存储过程、声明变量、for循环|转|
    Oracle 存储过程
    mybatis 调用存储过程 返回游标 实例
    Spring Aop实例
    Struts2之自定义类型转换器
  • 原文地址:https://www.cnblogs.com/csnd/p/11807837.html
Copyright © 2011-2022 走看看