python collections模块
collections模块基本介绍
collections在通用的容器dict,list,set和tuple之上提供了几个可选的数据类型
namedtuple() |
factory function for creating tuple subclasses with named fields |
deque |
list-like container with fast appends and pops on either end |
ChainMap |
dict-like class for creating a single view of multiple mappings |
Counter |
dict subclass for counting hashable objects |
OrderedDict |
dict subclass that remembers the order entries were added |
defaultdict |
dict subclass that calls a factory function to supply missing values |
UserDict |
wrapper around dictionary objects for easier dict subclassing |
UserList |
wrapper around list objects for easier list subclassing |
UserString |
wrapper around string objects for easier string subclassing |
namedtuple()
tuple类似于数组,只能通过下表来访问各个元素。使用namedtuple,每个元素有自己的名字,数据的意义一目了然。
In [22]: from collections import namedtuple In [23]: Point = namedtuple('Point', ['x', 'y']) In [24]: p = Point(11, y=22) In [25]: p[0] + p[1]
Out[25]: 33 In [26]: p.x
Out[26]: 11 In [27]: p.y
Out[27]: 22 In [28]: p
Out[28]: Point(x=11, y=22) In [29]: x, y = p In [30]: x
Out[30]: 11
命名元组还有三种额外的方法,两个属性
classmethod somenamedtuple.
_make
(iterable)
Class method that makes a new instance from an existing sequence or iterable.
从一个已经存在的序列或可迭代对象创建一个新实例
In [1]: from collections import namedtuple In [2]: Point = namedtuple('Point', ['x', 'y', 'z']) In [3]: t = [1, 2, 3] In [4]: p = Point._make(t) In [5]: p
Out[5]: Point(x=1, y=2, z=3)
somenamedtuple.
_asdict
()
Return a new OrderedDict
which maps field names to their corresponding values:
返回一个新的OrderedDict,并以field names作为key, field names对应值作为values。
In [16]: from collections import namedtuple In [17]: Point = namedtuple('Point', ['x', 'y', 'z']) In [18]: t = [1, 2, 3] In [19]: p = Point._make(t) In [20]: p
Out[20]: Point(x=1, y=2, z=3) In [21]: d = p._asdict() In [22]: d.get('x')
Out[22]: 1 In [23]: d
Out[23]: OrderedDict([('x', 1), ('y', 2), ('z', 3)])
somenamedtuple.
_replace
(kwargs)
Return a new instance of the named tuple replacing specified fields with new values:
返回一个用新值替换指定字段后的命名元组的一个新实例。
In [24]: from collections import namedtuple In [25]: Point = namedtuple('Point', ['x', 'y', 'z']) In [26]: t = [1, 2, 3] In [27]: p = Point._make(t) In [28]: p
Out[28]: Point(x=1, y=2, z=3) In [29]: p._replace(z=4)
Out[29]: Point(x=1, y=2, z=4) In [30]: p.z
Out[30]: 3 In [31]: p = p._replace(z=4) In [33]: p.z
Out[33]: 4 In [34]: p
Out[34]: Point(x=1, y=2, z=4)
somenamedtuple.
_fields
Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.
字段名列表
In [35]: p._fields
Out[35]: ('x', 'y', 'z')
somenamedtuple.
_source
A string with the pure Python source code used to create the named tuple class. The source makes the named tuple self-documenting. It can be printed, executed using exec()
, or saved to a file and imported.
创建命名元组的纯python代码
In [36]: p._source
Out[36]: "from builtins import property as _property, tuple as _tuple\nfrom operator import itemgetter as _itemgetter\nfrom collections import OrderedDict\n\nclass Point(tuple):\n 'Point(x, y, z)'\n\n __slots__ = ()\n\n _fields = ('x', 'y', 'z')\n\n def __new__(_cls, x, y, z):\n 'Create new instance of Point(x, y, z)'\n return _tuple.__new__(_cls, (x, y, z))\n\n @classmethod\n def _make(cls, iterable, new=tuple.__new__, len=len):\n 'Make a new Point object from a sequence or iterable'\n result = new(cls, iterable)\n if len(result) != 3:\n raise TypeError('Expected 3 arguments, got %d' % len(result))\n return result\n\n def _replace(_self, **kwds):\n 'Return a new Point object replacing specified fields with new values'\n result = _self._make(map(kwds.pop, ('x', 'y', 'z'), _self))\n if kwds:\n raise ValueError('Got unexpected field names: %r' % list(kwds))\n return result\n\n def __repr__(self):\n 'Return a nicely formatted representation string'\n return self.__class__.__name__ + '(x=%r, y=%r, z=%r)' % self\n\n def _asdict(self):\n 'Return a new OrderedDict which maps field names to their values.'\n return OrderedDict(zip(self._fields, self))\n\n def __getnewargs__(self):\n 'Return self as a plain tuple. Used by copy and pickle.'\n return tuple(self)\n\n x = _property(_itemgetter(0), doc='Alias for field number 0')\n\n y = _property(_itemgetter(1), doc='Alias for field number 1')\n\n z = _property(_itemgetter(2), doc='Alias for field number 2')\n\n"
OrderedDict()
字典都是是无序的,通过OrderedDict创建的字典会记住插入的顺序。
In [40]: from collections import OrderedDict In [41]: hexm = {'name': 'hexiaoming', 'age': 15, 'sexy': 'male'} In [42]: dict(hexm)
Out[42]: {'age': 15, 'name': 'hexiaoming', 'sexy': 'male'} In [43]: OrderedDict(hexm)
Out[43]: OrderedDict([('name', 'hexiaoming'), ('age', 15), ('sexy', 'male')])
In [44]: d1 = OrderedDict(hexm)
In [45]: d1['eat'] = 'gousi'
In [46]: d1
Out[46]:
OrderedDict([('name', 'hexiaoming'),
('age', 15),
('sexy', 'male'),
('eat', 'gousi')])
对字典排序:
In [47]: d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2} In [48]: OrderedDict(sorted(d.items(), key=lambda t: t[0]))
Out[48]: OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) In [49]: OrderedDict(sorted(d.items(), key=lambda t: t[1]))
Out[49]: OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]) In [50]: OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
Out[50]: OrderedDict([('pear', 1), ('apple', 4), ('banana', 3), ('orange', 2)])
python collections模块的更多相关文章
- Python collections模块总结
Python collections模块总结 除了我们使用的那些基础的数据结构,还有包括其它的一些模块提供的数据结构,有时甚至比基础的数据结构还要好用. collections ChainMap 这是 ...
- (转)python collections模块详解
python collections模块详解 原文:http://www.cnblogs.com/dahu-daqing/p/7040490.html 1.模块简介 collections包含了一些特 ...
- Python collections 模块用法举例
Python作为一个“内置电池”的编程语言,标准库里面拥有非常多好用的模块.比如今天想给大家 介绍的 collections 就是一个非常好的例子. 1.collections模块基本介绍 我们都知道 ...
- Python——collections模块、time模块、random模块、os模块、sys模块
1. collections模块 (1)namedtuple # (1)点的坐标 from collections import namedtuple Point = namedtuple('poin ...
- Python——collections模块
collections模块 collections模块在内置数据类型(dict.list.set.tuple)的基础上,还提供了几个额外的数据类型:ChainMap.Counter.deque.def ...
- python collections模块详解
参考老顽童博客,他写的很详细,例子也很容易操作和理解. 1.模块简介 collections包含了一些特殊的容器,针对Python内置的容器,例如list.dict.set和tuple,提供了另一种选 ...
- python collections模块 之 defaultdict
defaultdict 是 dict 的子类,因此 defaultdict 也可被当成 dict 来使用,dict 支持的功能,defaultdict 基本都支持.但它与 dict 最大的区别在于,如 ...
- python collections 模块 之 deque
class collections.deque(iterable[,maxlen]): 返回 由可迭代对象初始化的 从左向右的 deque 对象. maxlen: deque 的最大长度,一旦长度超出 ...
- python collections 模块 之namedtuple
namedtuple collections.namedtuple(typename, filed_name, *, rename=False, module=None) 创建一个以 typename ...
随机推荐
- Cocos2dx中线程优先级
Cocos2dx中线程优先级问题 不论是ios还是android,遇到耗时的任务都要另起线程处理,否则程序不能及时用户的反馈.游戏中如果一圈循环不能在1/frameRate(帧率是30则1/30)秒内 ...
- Undefined symbols for architecture arm64解决方案
在iOS开发中经常遇到的一个错误是Undefined symbols for architecture arm64,这个错误表示工程某些地方不支持arm64指令集.那我们应该怎么解决这个问题了?我们不 ...
- 最便捷的免费 SSL 证书解决方案(实测start SSL、Let's Encrypt、七牛免费SSL证书)
谷歌从 2017 年起,Chrome 浏览器将也会把采用 HTTP 协议的网站标记为「不安全」网站:苹果从 2017 年 iOS App 将强制使用 HTTPS:在国内热火朝天的小程序也要求必须使用 ...
- [Modern OpenGL系列(四)]在OpenGL中使用Shader
本文已同步发表在CSDN:http://blog.csdn.net/wenxin2011/article/details/51347440 在上一篇文章中已经介绍了OpenGL窗口的创建.本文接着说如 ...
- [数据分析]excel带名称的四象限散点图制作
本文前言:方法来至Excel图表之道这本数,偶然看到,好久没出数据分析的文章了,也难怪最近几个月都忙作网页,数据分析自己也就用excell和sql 正文: 带象限的散点图效果如下: 看到图片,这里制作 ...
- Unity 重要基础知识点
这是两个月前的学习记录,发出来了下,如果有误欢迎大家指出: 脚本生命周期 //每当脚本被加载时调用一次 // 1. 在Awake中做一些初始化操作 void Awake(){ //初始化publi ...
- MySQL高级特性
MySQL管理 用户管理 CREATE USER username IDENTIFIED BY 'password'; 新建用户 CREATE USER@'%' IDENTIFIED BY 'pass ...
- lombok在IntelliJ IDEA下的使用
lombok是一款可以精减java代码.提升开发人员生产效率的辅助工具,利用注解在编译期自动生成setter/getter/toString()/constructor之类的代码.代码越少,意味着出b ...
- 完整部署CentOS7.2+OpenStack+kvm 云平台环境(3)--为虚拟机指定固定ip
之前在测试环境(centos7.2)上部署了openstack云平台(完整部署CentOS7.2+OpenStack+kvm 云平台环境(1)--基础环境搭建),openstack在neutron组网 ...
- [LeetCode] Best Time to Buy and Sell Stock with Cooldown 买股票的最佳时间含冷冻期
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...