Collections
这个模块实现专门的容器数据类型提供替代Python的通用内置容器dict
,list
, set
,和tuple
。
-
namedtuple()
用于创建具有命名字段的元组子类工厂函数。
-
deque
类似列表的容器,可在两端进行快速的添加和删除。
-
Counter
用于对可hash对象计数的dict子类
-
OrderedDict
-
defaultDict
-
UserDict对象
-
UserList对象
-
UserString对象
namedtuple()
collections.namedtuple(typename,field_names ,verbose = False , rename = False)
返回名为typename的新元组子类。
field_names是一个字符串序列如[‘x’,‘y’],或者为单个字符串,每个字段名由空格’ ‘或逗号分隔’,’。
verbose=True,则在构建之前打印类定义。
rename=True,则无效的字段名称将自动替换为位置名称。
>>> from collections import namedtuple
>>> StuInfo = namedtuple('Student',"name grade age",verbose=True)
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict
class Student(tuple):
'Student(name, grade, age)'
__slots__ = ()
_fields = ('name', 'grade', 'age')
def __new__(_cls, name, grade, age):
'Create new instance of Student(name, grade, age)'
return _tuple.__new__(_cls, (name, grade, age))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new Student object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 3:
raise TypeError('Expected 3 arguments, got %d' % len(result))
return result
def _replace(_self, **kwds):
'Return a new Student object replacing specified fie