Python collections模块数据类型介绍

namedtuple

类似于能帮我们创建一个动态的类,使用该类我们可以动态指定属性和值,并且值只能定义一次,以后无法再修改,举例:

from collections import namedtuple

People = namedtuple("People", ["name", "age", "hobby"])
# 创建一个People类,含有name、age和hobby属性,并且属性值只能初始化的时候设置一次
people = People(name="aaa", age=10, hobby="play")
# people = People("aaa", 10, "play")
# 两种传参都可以
print(people)
print(people.name, people.age, people.hobby)
people.name = "xxx"
# 不能修改值
print(people.name, people.age, people.hobby)

# People(name='aaa', age=10, hobby='play')
# aaa 10 play
# AttributeError: can't set attribute
优势
  • 节省我们自己开发代码
  • 使用namedtuple创建的类会省掉很多不必要的变量,帮我们节省空间
  • 省内存、效率高
实现原理

该类实际上先编写了一个类的字符串模板,源码如下:

_class_template = """\
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict

class {typename}(tuple):
    '{typename}({arg_list})'

    __slots__ = ()

    _fields = {field_names!r}

    def __new__(_cls, {arg_list}):
        'Create new instance of {typename}({arg_list})'
        return _tuple.__new__(_cls, ({arg_list}))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new {typename} object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != {num_fields:d}:
            raise TypeError('Expected {num_fields:d} arguments, got %d' % len(result))
        return result

    def _replace(_self, **kwds):
        'Return a new {typename} object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, {field_names!r}, _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % list(kwds))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return self.__class__.__name__ + '({repr_fmt})' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values.'
        return OrderedDict(zip(self._fields, self))

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

{field_defs}
"""

以及创建属性的字符串模板:

_field_template = '''\
    {name} = _property(_itemgetter({index:d}), doc='Alias for field number {index:d}')
'''

然后通过格式化字符串后,通过exec函数动态创建类,通过该模板发现其还提供了几个方法,下面会介绍

提供方法
_make

类方法,接收一个迭代器创建对象,举例:

from collections import namedtuple

People = namedtuple("People", ["name", "age", "hobby"])
people = People._make(["aaa", 10, "play"])
# 传入一个可迭代对象创建对象
print(people)

# People(name='aaa', age=10, hobby='play')
_replace

修改指定属性值,并返回一个新的对象,举例:

from collections import namedtuple

People = namedtuple("People", ["name", "age", "hobby"])
people = People._make(["aaa", 10, "play"])
new_people = people._replace(name="bbb")
# 修改name,并返回一个新的对象
print(new_people)

# People(name='bbb', age=10, hobby='play')
_asdict

将类转成有序字典返回,举例:

from collections import namedtuple

People = namedtuple("People", ["name", "age", "hobby"])
people = People._make(["aaa", 10, "play"])
print(people._asdict())

# OrderedDict([('name', 'aaa'), ('age', 10), ('hobby', 'play')])

defaultdict

能够在key不存在的时候自动生成一个指定的对象(对象类型在我们实例化的时候传入):

from collections import defaultdict

dd = defaultdict(list)
# key不存在时,默认设置成一个list对象
print(dd["x"])
dd["x"].append(1)
print(dd["x"])

# []
# [1]

defaultdict初始化指定的类型必须是可调用的对象即可,例如:类、函数等,举例:

from collections import defaultdict

class A: pass

def people():
    return {
        "name": "aaa",
        "age": 20
    }

dd = defaultdict(people)
# 传入一个函数
print(dd["x"])
dd = defaultdict(A)
# 传入一个类
print(dd["x"])

# {'name': 'aaa', 'age': 20}
# <__main__.A object at 0x00000225A1A7F3C8>
实现原理

该类实现了__missing__魔法函数,当key不存在时就设置默认值

deque

双端队列,相比于list,提供了很多队头操作的方法,并且deque是线程安全的

Counter

对可迭代对象出现的次数进行统计:

from collections import Counter

a = ["a", "b", "a", "x", "a", "c", "b"]
c = Counter(a)
print(c)
print(c["a"])
# 查看a出现的次数
print(c.most_common(2))
# 取出数量最多的2个

# Counter({'a': 3, 'b': 2, 'x': 1, 'c': 1})
# 3
# [('a', 3), ('b', 2)]

该类继承自dict,因此可以用dict的相关方法

其他方法
most_common(n)

统计次数最多的前n个

elements

返回一个迭代器,里面是所有的内容

subtract

删掉几个元素,举例:

from collections import Counter

a = ["a", "b", "a", "x", "a", "c", "b"]
c = Counter(a)
print(c)
c.subtract(["a", "b"])
# 删掉一个a和一个b
print(c)

# Counter({'a': 3, 'b': 2, 'x': 1, 'c': 1})
# Counter({'a': 2, 'b': 1, 'x': 1, 'c': 1})

OrderDict

有序字典,但在python3.6以后普通的字典都是有序的了,不过该类还提供了一些dict没有的方法

提供方法
popitem

直接把最后一项弹出,举例:

from collections import OrderedDict

od = OrderedDict(a=1, b=2, c=3)
print(od)
print(od.popitem())
print(od)

# OrderedDict([('a', 1), ('b', 2), ('c', 3)])
# ('c', 3)
# OrderedDict([('a', 1), ('b', 2)])

该方法和pop不同,pop需要传入key,但该方法不需要,因为其内部维护了一个链表来记录顺序,然后将popitem时,直接把链表中最后一个弹出

remove_to_end

移动某个key到最后一个,举例:

from collections import OrderedDict

od = OrderedDict(a=1, b=2, c=3)
print(od)
od.move_to_end("a")
print(od)

# OrderedDict([('a', 1), ('b', 2), ('c', 3)])
# OrderedDict([('b', 2), ('c', 3), ('a', 1)])
原理

本质是内部维护了一个链表来记录顺序

chainmap

可以将多个可迭代对象合并到一起:

from collections import ChainMap

d1 = {"a":1, "b":2}
d2 = {"b":1, "c":2}
cm = ChainMap(d1, d2)
print(cm)
for d in cm:
    print(d, cm[d])

# ChainMap({'a': 1, 'b': 2}, {'b': 1, 'c': 2})
# c 2
# b 2
# a 1

可以看到如果有重名的,那么第一个会正常返回,而第二个就会被跳过,并且传入的对象只要是可迭代的即可,多个之间可以不是同一类型,举例:

from collections import ChainMap

d1 = [1,2,3]
d2 = {"a":1}
cm = ChainMap(d1, d2)
print(cm)
for d in cm:
    print(d)

# ChainMap([1, 2, 3], {'a': 1})
# 1
# 2
# 3
# a
原理

内部实际上就是将所有迭代器使用一个list包起来进行管理,源码如下:

def __init__(self, *maps):
    self.maps = list(maps) or [{}]          # always at least one map

因此我们也可以通过直接通过这个maps属性来进行操作,举例:

from collections import ChainMap

d1 = [1,2,3]
d2 = [1,4,5]
cm = ChainMap(d1, d2)
print(cm)
cm.maps[1][0] = 0
print(cm)

# ChainMap([1, 2, 3], [1, 4, 5])
# ChainMap([1, 2, 3], [0, 4, 5])

你可能感兴趣的:(Python collections模块数据类型介绍)