python 内置模块:collections
2018-07-29 13:47
926 查看
设置坐标:namedtuple格式: 变量名 = namedtuple(任意名,list)
双向队列:deque
https://docs.python.org/2.7/library/collections.html?highlight=deque#collections.deque
默认字典:defaultdict, 如果没有该key值,默认输出指定值。
顺序排列dist: OrderedDict
计算数目:Counter
from collections import namedtuple Point = namedtuple('point', ['x', 'y', 'z']) p = Point(1,2,0) print(p.x) print(p.y, p.z) print(isinstance(p, tuple))运行结果:
1 2 0 True
双向队列:deque
https://docs.python.org/2.7/library/collections.html?highlight=deque#collections.deque
from collections import deque q = deque(['a', 'b', 'c']) q.append('x') #尾插 q.appendleft('y') #头插 print(q)运行结果:
deque(['y', 'a', 'b', 'c', 'x'])
默认字典:defaultdict, 如果没有该key值,默认输出指定值。
from collections import defaultdict dd = defaultdict(lambda: 'N/A') dd['key1'] = 'abc' print (dd['key1']) # key1存在 print (dd['key2'])运行结果:
abc N/A
顺序排列dist: OrderedDict
from collections import OrderedDict d = dict([('a', 1), ('b', 2), ('c', 3)]) n = {'a':1, 'b':2, 'c':3} print (d) # dict的Key是无序的 print (n) # dict的Key是无序的 od = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) print (od)# OrderedDict的Key是有序的运行结果:
{'c': 3, 'b': 2, 'a': 1} {'c': 3, 'b': 2, 'a': 1} OrderedDict([('a', 1), ('b', 2), ('c', 3)])
计算数目:Counter
from collections import Counter c = Counter() for ch in 'programming': c[ch] = c[ch] + 1 print(c) print(c)运行结果:
Counter({'p': 1}) Counter({'r': 1, 'p': 1}) Counter({'r': 1, 'o': 1, 'p': 1}) Counter({'r': 1, 'o': 1, 'p': 1, 'g': 1}) Counter({'r': 2, 'o': 1, 'p': 1, 'g': 1}) Counter({'r': 2, 'o': 1, 'p': 1, 'g': 1, 'a': 1}) Counter({'r': 2, 'o': 1, 'p': 1, 'g': 1, 'a': 1, 'm': 1}) Counter({'r': 2, 'm': 2, 'o': 1, 'p': 1, 'g': 1, 'a': 1}) Counter({'r': 2, 'm': 2, 'o': 1, 'i': 1, 'p': 1, 'g': 1, 'a': 1}) Counter({'r': 2, 'm': 2, 'o': 1, 'i': 1, 'n': 1, 'p': 1, 'g': 1, 'a': 1}) Counter({'r': 2, 'g': 2, 'm': 2, 'o': 1, 'i': 1, 'n': 1, 'p': 1, 'a': 1}) Counter({'r': 2, 'g': 2, 'm': 2, 'o': 1, 'i': 1, 'n': 1, 'p': 1, 'a': 1})
相关文章推荐
- Python提供了以下几个内置tools模块:operator collections itertools functools
- Python系列之Collections内置模块(2)
- Python系列之Collections内置模块(2)
- Python学习笔记(三十三)常用内置模块(2)collections_namedtuple_deque_defaultdict_OrderedDict_Counter
- Python中Collections模块的Counter容器类使用教程
- Python_Day_5装饰器、字符串格式化、序列化、内置模块、生成器、迭代器之篇
- Python 2.7.9+ and 3.4+ 安装模块不再需要单独安装 pip ,Python 已经内置了 pip 安装工具
- 《每日一课》Python入门之datetime内置模块的使用
- Python内置模块之time、random、hashlib、OS、sys、UUID模块
- python内置的urllib模块不支持https协议的解决办法
- Python 内置 time 模块 API 中文档案
- Python中Collections模块的Counter容器类使用教程
- Python常用内置模块之xml模块
- python内置正则表达式(re)模块官方文档简要中文版
- python内置模块(三)
- 简单掌握Python的Collections模块中counter结构的用法
- Python内建模块collections
- Python内置的urllib模块不支持https协议的解决办法
- Python的collections模块中的OrderedDict有序字典
- python模块collections中namedtuple()的理解