Python其他数据结构collection模块-namtuple defaultdict deque Queue Counter OrderDict

nametuple

  是tuple扩展子类,命名元组,其实本质上简单类对象

from collections import namedtuple

info = namedtuple("Info", [‘name‘, ‘age‘, ‘height‘])
# 赋值,是不是有点像面向对象中实例变量方式
info.name = "北门吹雪"
info.age = 18
info.height = 175

# 访问
print(info.name)

  其实本质上和下面方式一样

class Info:
    def __init__(self):
        self.name = None
        self.age = None
        self.height = None
        pass

info = Info()
# 赋值
info.name = "北门吹雪"
info.age = 18
info.height = 175
# 访问
print(info.name)

  相关方法

    1. _make 初始化赋值, 必须长度一致

from collections import namedtuple

info = namedtuple("Info", [‘name‘, ‘age‘, ‘height‘])._make(["北门吹雪", 18, 175])

# 访问
print(info.name)

    2. _asdict  将nametuple对象转换为字典对象,是个有序字典

from collections import namedtuple

info = namedtuple("Info", [‘name‘, ‘age‘, ‘height‘])._make(["北门吹雪", 18, 175])

# 访问
print(info._asdict())

  

  

defaultdict

  是dict的扩展类,访问字典的key如果没有则自动设置默认值,并添加进字典

info = dict()
name = info.setdefault(‘name‘, "北门吹雪")
print(name, info)

from collections import defaultdict
# 默认值必须是可迭代对象
info = defaultdict(lambda: "北门吹雪")
name = info[‘name‘]
print(name, info)

  

deque  

  双端队列, 操作和list类似

  list deque 推荐用来保存相同类似数据,相关方法和list一致

  特性: deque是线程安全的,list不是线程安全,多线程编程则使用deque

from collections import deque
names = deque()
names.append("北门吹雪")
names.append("QiNiuYun")
names.insert(0, "今日头条")
print(names)

  

Queue    

  队列(先进先出),通过 deque实现

  核心两个方法 put get,会堵塞

from queue import Queue

message = Queue()
# 放入数据
message.put("北门吹雪")
# 消费数据
print(message.get())

  

Counter  

  对可迭代对象做统计出现个数,直接返回统计结果,是dict的子类

from collections import Counter
from random import randint

numbers = [randint(1, 5) for _ in range(20)]
numbers_count = Counter(numbers)
print(numbers_count)

  相关方法

    1. update        添加新的数据

from collections import Counter
from random import randint

numbers = [randint(1, 5) for _ in range(20)]
numbers_count = Counter(numbers)
print(numbers_count)
# 添加新的数据
numbers_count.update([randint(1, 10) for _ in range(20)])
print(numbers_count)

    2. most_common(N)   输出出现次数当前最多的前N个元素

from collections import Counter
from random import randint

numbers = [randint(1, 5) for _ in range(20)]
numbers_count = Counter(numbers)
print(numbers_count)
# 添加新的数据
numbers_count.update([randint(1, 10) for _ in range(20)])
print(numbers_count)

# 输出出现次数当前最多的前3个元素,返回列表
print(numbers_count.most_common(3))

  

OrderDict

  继承dict, 保持字典添加顺序,具有dict所有方法

from collections import OrderedDict

info = OrderedDict()
# 填入数据
info["name"] = "北门吹雪"
info[‘age‘] = 18
info[‘height‘] = 175
print(info)

  其他方法

    1. popitem    默认删除最后的key:value,并返回

from collections import OrderedDict

info = OrderedDict()
# 填入数据
info["name"] = "北门吹雪"
info[‘age‘] = 18
info[‘height‘] = 175
# 返回元组形式
print(info.popitem(‘name‘))

    2. pop      必须传入key,删除key:value,返回value

from collections import OrderedDict

info = OrderedDict()
# 填入数据
info["name"] = "北门吹雪"
info[‘age‘] = 18
info[‘height‘] = 175

# 返回age对应的值
print(info.pop(‘age‘))

    3. move_to_end   传入key,将元素移到最后

from collections import OrderedDict

info = OrderedDict()
# 填入数据
info["name"] = "北门吹雪"
info[‘age‘] = 18
info[‘height‘] = 175

# 移动数据
info.move_to_end(‘age‘)
print(info)

  

经验:

  1. 这些数据类型基础还是从list tuple set dict基本数据类型扩展而来,本质上添加了一些特性

原文地址:https://www.cnblogs.com/2bjiujiu/p/9141431.html

时间: 2024-07-29 21:27:25

Python其他数据结构collection模块-namtuple defaultdict deque Queue Counter OrderDict的相关文章

Python高级数据结构-Collections模块

在Python数据类型方法精心整理,不必死记硬背,看看源码一切都有了之中,认识了python基本的数据类型和数据结构,现在认识一个高级的:Collections 这个模块对上面的数据结构做了封装,增加了一些很酷的数据结构,比如: a)Counter: 计数器,用于统计元素的数量 b)OrderDict:有序字典 c)defaultdict:值带有默认类型的字典 d)namedtuple:可命名元组,通过名字来访问元组元素 e)deque :双向队列,队列头尾都可以放,也都可以取(与单向队列对比,

python collection模块中几种数据结构(Counter、OrderedDict、namedtup)

collection模块中有几种数据结构我们可能用得到. Counter是字典的子类,负责计数的一个字典,支持 + 加法 - 减法 & 求公共元素 | 求并集 print('Counter类型的应用') c = Counter("dengjingdong") #c = Counter({'n': 3, 'g': 3, 'd': 2, 'i': 1, 'o': 1, 'e': 1, 'j': 1}) print("原始数据:",c) print("最

Python进阶(十)----规范化格式目录, time模块, datatime模块,random模块,collection模块(python额外数据类型)

Python进阶(十)----规范化格式目录, time模块, datatime模块,random模块,collection模块(python额外数据类型) 一丶规范化格式目录 六个目录: #### 对某某项目进行一个标准化的开发,进行规范化. #bin : 启动项目程序的主入口 #conf : 项目的配置文件 #core : 主要逻辑(业务逻辑) #db : 存放数据() #lib : 辅助文件(存放公共的一些方法) #README : 项目文档说明 ? 二丶time模块(时间模块) 时间的三

简介Python的collections模块中defaultdict类型

这里我们来简介Python的collections模块中defaultdict类型的用法,与内置的字典类最大的不同在于初始化上,一起来看一下: defaultdict 主要用来需要对 value 做初始化的情形.对于字典来说,key 必须是 hashable,immutable,unique 的数据,而 value 可以是任意的数据类型.如果 value 是 list,dict 等数据类型,在使用之前必须初始化为空,有些情况需要把 value 初始化为特殊值,比如 0 或者 ''. from c

python基础31[常用模块介绍]

python基础31[常用模块介绍] python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的libraries(modules)如下: 1)python运行时服务 * copy: copy模块提供了对复合(compound)对象(list,tuple,dict,custom class)进行浅拷贝和深拷贝的功能. * pickle: pickle模块被用来序列化python的对象到bytes流,从

python中的各个模块

collection模块:python中的扩展数据模块#namedtuple: 生成可以使用名字来访问元素内容的tuple'''from collections import namedtuplePoint=namedtuple('point',['x','y']) #必须起名字 pointp=Point(1,2)print(p.x) #表示坐标中的x点print(p.y)print(p) #point(x=1, y=2) 表示坐标'''#deque 双端队列,快速的从另外一侧追加和推出对象 适

Python 中的collections 模块

这个模块中实现了一些类,非常灵活.可以用于替代python 内置的dict .list .tuple .set 类型.并且一些功能是这些内置类型所不存在的. 在网络上找了一些资料,重点说说collections 模块中的 deque .defaultdict.Counter 类 1.class deque类似于python 内置的 list ,不过它是一个双向的list.可以在任意一头进行操作 help(collections.deque) class deque(__builtin__.obj

Python 运维常用模块

基础库:sys.os(os.path.os.stat).time.logging.prarmiko.re.random Python运维常用的20个库 1.psutil是一个跨平台库(https://github.com/giampaolo/psutil)能够实现获取系统运行的进程和系统利用率(内存,CPU,磁盘,网络等),主要用于系统监控,分析和系统资源及进程的管理. 2.IPy(http://github.com/haypo/python-ipy),辅助IP规划. 3.dnspython(h

Python基础5-常用模块

本节大纲 模块介绍 time &datetime模块 random os sys shutil shelve xml处理 yaml处理 configparser hashlib subprocess logging模块 re正则表达式 模块,就是实现某种或者某类功能代码的合集. 类似于函数式编程和面向过程编程,函数式编程完成一个功能,其他代码可以调用,提供了代码的重用性跟代码间的耦合.对于一个复杂的功能,可能需要多个函数才能完成,多个.py文件的代码集合就叫做模块. 如:os是系统相关的模块:f