Python其他数据结构collection模块-namtuple defaultdict deque Queue Counter OrderDict arrary
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)
arrary
只能存放一种类型的数组,这个数组高性能非常高,非常类似list除了只能存放一种类型数据
#标识符 存放数据类型 占用字节
'u' Unicode字符 2
“L” 符号整数 4
“L” 无符号整数 4
“q” 符号整数 8
“q” 无符号整数 8
F ′浮点 4
“D” 浮点 8
import array
names = array.array("u")
print(names.append("北"))
print(names.append("门"))
print(names.append("吹"))
print(names.append("雪"))
print(names)
print(names[1])
经验:
1. 这些数据类型基础还是从list tuple set dict基本数据类型扩展而来,本质上添加了一些特性
2. 不同的情况下选择不同的数据结构对数据进行处理
北门吹雪: https://www.cnblogs.com/2bjiujiu/
Python其他数据结构collection模块-namtuple defaultdict deque Queue Counter OrderDict arrary的更多相关文章
- Python高级数据结构-Collections模块
在Python数据类型方法精心整理,不必死记硬背,看看源码一切都有了之中,认识了python基本的数据类型和数据结构,现在认识一个高级的:Collections 这个模块对上面的数据结构做了封装,增加 ...
- Python原生数据结构增强模块collections
collections简介 python提供了4种基本的数据结构:list.tuple.dict.set.基本数据结构完全可以hold住所有的场景,但是在处理数据结构复杂的场景时,这4种数据结构有时会 ...
- Python常用数据结构之collections模块
Python数据结构常用模块:collections.heapq.operator.itertools collections collections是日常工作中的重点.高频模块,常用类型由: 计数器 ...
- Python collection模块与深浅拷贝
collection模块是对Python的通用内置容器:字典.列表.元组和集合的扩展,它包含一些专业的容器数据类型: Counter(计数器):dict子类,用于计算可哈希性对象的个数. Ordere ...
- Python常用数据结构之heapq模块
Python数据结构常用模块:collections.heapq.operator.itertools heapq 堆是一种特殊的树形结构,通常我们所说的堆的数据结构指的是完全二叉树,并且根节点的值小 ...
- python双端队列-collection模块
双端队列(double-ended queue,或者称deque)在需要按照元素增加的顺序来移除元素时非常有用.其中collection模块,包括deque类型. 使用实例:
- Python进阶(十)----软件开发规范, time模块, datatime模块,random模块,collection模块(python额外数据类型)
Python进阶(十)----软件开发规范, time模块, datatime模块,random模块,collection模块(python额外数据类型) 一丶软件开发规范 六个目录: #### 对某 ...
- (python数据分析)第03章 Python的数据结构、函数和文件
本章讨论Python的内置功能,这些功能本书会用到很多.虽然扩展库,比如pandas和Numpy,使处理大数据集很方便,但它们是和Python的内置数据处理工具一同使用的. 我们会从Python最基础 ...
- python-Day3-set 集合-counter计数器-默认字典(defaultdict) -可命名元组(namedtuple)-有序字典(orderedDict)-双向队列(deque)--Queue单项队列--深浅拷贝---函数参数
上节内容回顾:C语言为什么比起他语言块,因为C 会把代码变异成机器码Pyhton 的 .pyc文件是什么python 把.py文件编译成的.pyc文件是Python的字节码, 字符串本质是 字符数组, ...
随机推荐
- git ssh配置
SSH KEY的配置 生成 SSH KEY ssh-keygen -t rsa -b 4096 -C "your_email@example.com" 文件在哪里生成的 C:\用户 ...
- vue 在模板template中变量和字符串拼接
例子: :post-action="'/api/v1/reportPage/'+this.selectedPagerId+'/saveimg/'"
- 整理最全的Android开发工程师面试题,面试题详解。java、Android程序员
1. 请描述下Activity的生命周期. 必调用的三个方法:onCreate()--> onStart() --> onResume(),用AAA表示 (1)父Activity启动 ...
- 【C#】静态构造方法与静态变量
扯下闲篇先,本来今天预计整理下委托.事件.Lamada的笔记,然后再把单例模式的懒汉.饿汉模式看完. 在看到懒汉的双重加锁设计时,向同桌贩卖了下该设计的优点,结果反被同桌的一个问题难倒了~! 一. 有 ...
- 网址中的静态资源 public
客户端浏览器收到的HTML响应内容中如果带有 link img script video audio 等带有src或者href标签时候,这些都是外部链接资源请求url.浏览器会默认自动性的对这些资源 ...
- Java中nextInt和nextLine同时使用出现的问题
代码: package com.ins1; import java.util.*; public class test { public static void main(String[] args) ...
- leetcode刷题-57插入区间
题目 给出一个无重叠的 ,按照区间起始端点排序的区间列表. 在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间). 示例 1: 输入:intervals = ...
- Mybatis-日志
日志 目录 日志 1. 日志工厂 1. STDOUT_LOGGING标准日志输出 2. LOG4J 1. 先导入Log4J的包 2. log4j.properties 3. 配置log4j为日志的实现 ...
- pyhton:time模块和datetime模块
一.time模块 1.相关定义: time模块时间的表达有3种,时间戳,时间元祖,格式化时间 #时间戳: print(time.time())#获取当前时间戳.时间戳的计算是1970纪元后经过的浮点秒 ...
- IDEA中配置Tomcat中的Artifact
IDEA中配置Tomcat中的Artifact 我在配置Tomcat时,要设置deployment中的Artifact时,却总是无法显示出当前项目的war包,针对这个问题,如下图展示, 当我点击Art ...