collections — 容器数据类型

源代码: Lib/collections/__init__.py


此模块实现专用容器数据类型,提供备选为 Python 一般目的内置容器 dict , list , set ,和 tuple .

namedtuple()

采用命名字段创建 tuple 子类的工厂函数

deque

两端都能快速追加和弹出的像 list 容器

ChainMap

用于创建多映射的单个视图的像 dict 类

Counter

dict subclass for counting hashable 对象

OrderedDict

能记住条目添加次序的 dict 子类

defaultdict

调用工厂函数以提供缺少值的 dict 子类

UserDict

围绕字典对象的包裹器为更易于 dict 子类化

UserList

围绕列表对象的包裹器,为更容易 list 子类化

UserString

围绕字符串对象的包裹器为更易于字符串子类化

ChainMap 对象

Added in version 3.3.

A ChainMap 类是为快速链接很多映射而提供的,因此可以将它们视为单个单元。它通常快得多,比创建新字典并运行多个 update() 调用。

此类可以用于模拟嵌套作用域,且在模板中很有用。

class 集合。 ChainMap ( * maps )

A ChainMap 将多个字典 (或其它映射) 分组在一起,以创建单个、可更新视图。若没有 maps 被指定,将提供单个空字典,以便新链始终至少拥有一个映射。

底层映射存储在列表中。列表是公共的,且访问 (或更新) 可以使用 maps 属性。没有其它状态。

依次查找搜索底层映射,直到找到键。相比之下,写入、更新及删除仅运转于第一映射。

A ChainMap 通过引用吸收底层映射。因此,如果某个底层映射获得更新,这些改变将反映在 ChainMap .

通常支持所有字典方法。此外,还有 maps 属性、用于创建新的子上下文的方法、及用于访问所有映射 (除第 1 映射外) 的特性:

maps

A user updateable list of mappings. The list is ordered from first-searched to last-searched. It is the only stored state and can be modified to change which mappings are searched. The list should always contain at least one mapping.

new_child ( m = None , ** kwargs )

返回新的 ChainMap containing a new map followed by all of the maps in the current instance. If m is specified, it becomes the new map at the front of the list of mappings; if not specified, an empty dict is used, so that a call to d.new_child() 相当于: ChainMap({}, *d.maps) . If any keyword arguments are specified, they update passed map or new empty dict. This method is used for creating subcontexts that can be updated without altering values in any of the parent mappings.

3.4 版改变: 可选 m 参数被添加。

3.10 版改变: Keyword arguments support was added.