python常用collections lib介绍
来源:互联网 发布:org.w3c.dom.node 编辑:程序博客网 时间:2024/06/09 15:30
简介
本文主要介绍python3下collections lib。主要lib如下:- Counter- defaultdict- deque- OrderedDict- namedtuple- ChainMapCounter
计算出现次数>>> import collections>>> collections.Counter([1,1,2,3,4,4,4,5])Counter({4: 3, 1: 2, 2: 1, 3: 1, 5: 1})>>> collections.Counter("huuinn")Counter({'n': 2, 'u': 2, 'h': 1, 'i': 1})
defaultdict
当对应的键值不存在时,返回默认值,而不是报错
>>> import collections>>> d = collections.defaultdict(int)>>> d[0]0>>> d[2]0>>> d = collections.defaultdict(lambda:100) # 想默认值非0时返回100时>>> d[1]100>>> d[11]100>>> d = dict()>>> d[0]Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: 0
deque
可双向操作的队列>>> import collections>>> d = collections.deque([1,2,3,4])>>> d.pop()4>>> d.popleft()1>>> ddeque([2, 3])>>> d.appendleft(4)>>> d.append(1)>>> ddeque([4, 2, 3, 1])
OrderedDict
值按顺序添加到对象里>>> import collections>>> o = collections.OrderedDict()>>> o['first']=1>>> o['second']=2>>> oOrderedDict([('first', 1), ('second', 2)])>>> o['second']=3>>> oOrderedDict([('first', 1), ('second', 3)])
namedtuple
让tuple类型的元素当作类成员属性来访问>>> import collections>>> N = collections.namedtuple('Fruit',['apple','grape'])>>> N(*[1,2])Fruit(apple=1, grape=2)>>> n = N(*[1,2])>>> nFruit(apple=1, grape=2)>>> n.apple1>>> n.grape2
ChainMap
多个字典合并>>> import collections>>> c = collections.ChainMap({1:2,3:4},{5:6,7:8})>>> c = c.new_child({9:10,11:12})>>> cChainMap({9: 10, 11: 12}, {1: 2, 3: 4}, {5: 6, 7: 8})>>> c[9]10>>> c.maps[{9: 10, 11: 12}, {1: 2, 3: 4}, {5: 6, 7: 8}]>>> c.maps[0]{9: 10, 11: 12}
查看原文:https://www.huuinn.com/archives/500
更多技术干货:风匀坊
关注公众号:风匀坊
阅读全文
0 0
- python常用collections lib介绍
- python - collections模块基本介绍
- System.Collections 的常用集合介绍
- Python常用模块re,collections,random
- Python基础-常用内建模块 collections
- Python collections
- python Collections
- collections python
- python常用模块介绍
- python 常用模块介绍
- Python常用模块介绍
- Python 常用功能模块介绍
- Python常用模块介绍
- python常用模块介绍
- Python 常用模块介绍
- python 常用模块介绍
- Python常用内建模块—datetime\collections\struct
- Python 常用标准库介绍
- 设计模式的艺术之道--桥接模式
- 【ORACLE】物化视图快速刷新限制条件
- FlatList的点击Demo
- Android进阶-Android动画机制与使用技巧
- LC-selfDividingNumber
- python常用collections lib介绍
- UBOOT中环境变量的类别
- 卷积核问题
- docker attch退出
- iview
- Eclipse中web项目部署至Tomcat步骤【整理】
- visio怎么保存为图片?
- Android 半边圆角ImageView
- CString与char之间的转换