Python 的collections模块
2019-01-20 17:04
375 查看
在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。
目录
namedtuple: 生成可以使用名字来访问元素内容的tuple
Counter : 计数器,主要用来记录每一个元素出现的次数
OrderedDict : 有序字典 (对于3.6版本以后的Python 的作用不是很大,因为此版本的字典默认是有序)
namedtuple: 生成可以使用名字来访问元素内容的tuple
[code]from collections import namedtuple Point = namedtuple('Point',['x','y']) #创建模板 # namedtuple("名称",【属性list】) p = Point(1,2) #传入内容 print(p.x) #结果是 :1 print(p.y) #结果是 :2
deque: 双端队列,可以快速的在两端追加和推出对象
[code]from collections import deque q = duque(['a','b','c']) q.append('x') q.leftappend('1') #向列表的头部添加元素 q.pop() ##弹出列表的尾部最后一个元素 q.leftpop() #弹出列表的头部第一个元素 print(q) #结果是 ['a','b','c']
Counter : 计数器,主要用来记录每一个元素出现的次数
[code]from collections import Counter c = Counter(['a','b','c','c']) print(c) #结果 Counter({'c': 2, 'a': 1, 'b': 1})
OrderedDict : 有序字典 (对于3.6版本以后的Python 的作用不是很大,因为此版本的字典默认是有序)
defalutdict : 带有默认值的字典
作用:在使用dict时,如果引用的Key不存在,就会抛出KeyEroor,如果希望key不存在时,返回一个默认值,就可以使用defalutdict
[code]from collections import defaultdict dd = defaultdict(lambda: 'N/A') dd['key1'] = 'abc' print(dd['key1']) #键存在 结果是: 'abc' print(dd['key2']) #键不存在 结果是:'N/A'
相关文章推荐
- Python中Collections模块的Counter容器类使用教程
- python的常用模块之collections模块详解
- python模块学习之数据结构--collections.counter
- Python常用内建模块—datetime\collections\struct
- Python常用模块re,collections,random
- 详解Python的collections模块中的deque双端队列结构
- 简介Python的collections模块中defaultdict类型的用法
- python的常用模块之collections模块
- python常见模块之collections模块
- Python collections模块简介
- python 常用的模块(collections)转
- Python学习笔记-4(模块:collections、itertools、xml)
- Python高级数据类型模块collections
- Python 之 统计模块collections
- Python Collections 模块学习
- Python collections模块
- python内建模块之collections
- 不可不知的Python模块: collections
- Python中Collections模块的Counter容器类使用教程
- python collections模块