Python标准库—collections模块

Python collections模块包含多种专门的容器数据类型,如namedtuple、Counter、deque等。namedtuple用于创建带命名字段的元组子类,deque是支持快速添加和删除的双端队列,Counter是用于计数的字典子类,而OrderedDict、defaultDict则是特殊的字典实现。UserDict、UserList和UserString则提供自定义映射和序列类型的基类。
摘要由CSDN通过智能技术生成

Collections

这个模块实现专门的容器数据类型提供替代Python的通用内置容器dictlistset,和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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值