Python 学习之常用内建模块(collections)

collections 是 Python 内建的一个集合模块,提供了许多有用的集合类。

namedtuple

namedtuple 是一个函数,它用来创建一个自定义的 tuple 对象,并且规定了 tuple 元素的个数,并可以用属性而不是索引来引用 tuple 的某个元素。
这样一来,我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' 内建模块—collections '

__author__ = 'Kevin Gong'

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print('Point:', p.x, p.y)

deque

deque 是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' 内建模块—collections '

__author__ = 'Kevin Gong'

from collections import deque

q = deque(['a', 'b', 'c'])
q.append('x')
q.appendleft('y')
print(q)

defaultdict

使用 dict 时,如果引用的 Key 不存在,就会抛出 KeyError。如果希望 key 不存在时,返回一个默认值,就可以用 defaultdict:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' 内建模块—collections '

__author__ = 'Kevin Gong'

from collections import defaultdict

dd = defaultdict(lambda: 'N/A')
dd['key1'] = 'abc'
print('dd[\'key1\'] =', dd['key1'])
print('dd[\'key2\'] =', dd['key2'])

Counter

Counter是一个简单的计数器,例如,统计字符出现的个数:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' 内建模块—collections '

__author__ = 'Kevin Gong'

from collections import Counter

c = Counter()
for ch in 'hello kevin':
    c[ch] = c[ch] + 1
print(c)

结果:

Counter({'e': 2, 'l': 2, 'h': 1, 'o': 1, ' ': 1, 'k': 1, 'v': 1, 'i': 1, 'n': 1})

猜你喜欢

转载自blog.csdn.net/duoduo_11011/article/details/106463326