zoukankan      html  css  js  c++  java
  • Python_collections模块

    collections 模块----Python标准库,是数据结构常用模块

    常用类型有:

      计数器(Counter)

      双向队列(deque)

      默认字典(defaultdict)

      有序字典(OrderedDict)

      可命名元组(namedtuple)

    一、Counter

    主要功能:将元素数量统计,然后计数返回一个字典,键为元素,值为元素个数

    #!/usr/bin/env python3
    # -*- coding: UTF-8 -*-
    # a = 532423
    # print(bytes(a)) #d字节型数组
    # a = 234234
    # print(bytearray(a)) #d字数数组
    #
    from collections import  Counter
    
    str="abcbcaccbbad"
    li=[2,3,43,3,45,54,33,33,1]
    d={'d':3,'f':4,'g':3,'h':5}
    
    #获取元素个数,返回字典
    print(dict(Counter(str)))
    print(dict(Counter(d)))
    print(dict(Counter(li)))
    
    #most_common(int) 按照元素出现的次数进行从高到低的排序,返回前int个元素的字典
    print(Counter(str).most_common(2))
    
    #elements返回经过计算器Counter后的元素,返回的是一个迭代器
    print(''.join(Counter(str).elements()))
    
    #update更新,做加法,加上对应的个数
    x=Counter(str)
    x.update("sas1")
    print(dict(x))
    
    #subtract,做减法,减去对于的个数
    y=Counter(li)
    y.subtract([3,2])
    print(dict(y))
    print(y)
    
    #获取key和value
    print(list(Counter(str).items())) #字典的key和value
    print(list(Counter(str).keys())) #字典的key
    print(list(Counter(str).values())) #字典的value
  • 相关阅读:
    提交暂存更改时报 is outside repository 解决办法
    vue 路由跳转传参
    Unexpected token u in JSON at position 0 解决
    解决element table错位的问题
    使用docker制作Mysql镜像
    Linux系统性能排查
    分盘挂载
    Shell中的变量
    Shell流程控制
    Shell条件判断
  • 原文地址:https://www.cnblogs.com/insane-Mr-Li/p/13265680.html
Copyright © 2011-2022 走看看