Python中的collections模块
文章目录
- Python中的collections模块
- 1.Counter对象
- 2.deque对象
- 3.defaultdict对象
- 4.namedtuple
- 5.OrderedDict
- Reference
 
 
Python中的
collections提供许多容器数据类型,这个模块实现了一些专门化的容器,提供了对Python的通用内建容器 
dict、 
list、 
set和 
tuple的补充。 
 
| 容器 | 功能 | 
|---|---|
| namedtuple() | 一个工厂函数,用于创建元组的子类 | 
| deque | 类似列表的队列,但 append和pop在其两端的速度都极快 | 
| ChainMap | 类似字典的类,用于创建包含多个映射的单个视图 | 
| Counter | 用于计数hashable对象的字典子类 | 
| OrderedDict | 字典的子类,能记住条目被添加的顺序 | 
| defaultDict | 字典的子类,通过调用用户指定的工厂函数,为键提供默认值 | 
| UserDict | 封装了字典对象,简化了字典子类化 | 
| UserList | 封装了列表对象,简化了列表子类化 | 
| UserString | 封装了字符串对象,简化了字符串子类化 | 
1.Counter对象
Counter是一个计数器工具,目的是为了快速记账,例如:
from collections import Counter
cnt: Counter = Counter()
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
for word in words:cnt[word] += 1
print(cnt)
>> Counter({'apple': 3, 'banana': 2, 'orange': 1})
Counter可以将元素储存为字典的键而它们的计数储存为字典的值。计数可以为任何整数,包括零或负的计数值。
Counter可以使用如下的方式来进行初始化
c = Counter()                           # a new, empty counter
c = Counter('gallahad')                 # a new counter from an iterable
c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
c = Counter(cats=4, dogs=8)             # a new counter from keyword args
如果查询的值不在Counter中,则会返回0,而不是像字典以用返回一个KeyError。
c = Counter(cats=4, dogs=8)             # a new counter from keyword args
c['birds']
>>> 0
设置一个计数为0,并不会从Counter中删除它,若要删除它则使用del
c = Counter(cats=4, dogs=8)             # a new counter from keyword args
c['cats'] = 0
del c['dogs']
print(c)
Counter({'cats': 0})
2.deque对象
deque是一种双端队列[double end queue],我们可以利用这个双端队列来实现数据结构中的栈stack和队列queue。deque支持以下方法:
| 方法 | 功能 | 
|---|---|
| append(x) | 将 x添加到右端 | 
| appendleft(x) | 将 x添加到左端 | 
| clear() | 移除所有元素,使其长度为0 | 
| copy() | 创建一份浅拷贝 | 
| count(x) | 统计 deque中元素等于x的个数 | 
| extend(iterable) | 拓展 deque的右侧,通过添加iterable参数中的元素 | 
| extendleft(iterable) | 拓展 deque的左侧,通过添加iterable参数中的元素 | 
| index(x[, start[, stop]]) | 返回 x在deque中的位置(在索引start之后,在索引stop之前) | 
| insert(i, x) | 在 i的位置插入x | 
| pop() | 移除并且返回 deque最右端的元素 | 
| popleft() | 移除并且返回 deque最左端的元素 | 
| remove(value) | 移除找到的第一个 value | 
| reverse() | 将 deque逆序排列 | 
| rotate(n=1) | 向右循环移动 n步,如果n是负数,则向左循环,如果deque不是空的,向右循环移动一步就等价于d.appendleft(d.pop()), 向左循环一步就等价于d.append(d.popleft())。 | 
| maxlen | 返回deque的最大尺寸 | 
以下是一个使用示例
from collections import deque
d: deque = deque('efg')     # make a new deque with three items
for item in d:print(item)
>>>
"""
e
f
g
"""
d.append('h')				# add a new entry to the right side
d.appendleft('d')			# add a new entry to the left side
print(d)					# show the representation of the deque
>>>	
"""
deque(['d', 'e', 'f', 'g', 'h'])
"""
print(d.pop())				# return and remove the rightmost item
print(d.popleft())			# return and remove the leftmost item
print(d)
>>>
"""
h
d
deque(['e', 'f', 'g'])
"""
print(d[0])					# peek at leftmost item
print(d[-1])				# peek at rightmost item
>>>
"""
e
g
"""
d.extend('hij')				# add multiple elements to right at once
d.extendleft('cba')			# add multiple elements to left at once
print(d)
>>>
"""
deque(['a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j'])
"""
d.rotate(1)					# right rotation
print(d)
>>>
"""
deque(['j', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i'])
"""
d.rotate(-1)				# left rotation
print(d)					
>>>
"""
deque(['a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j'])
"""
3.defaultdict对象
在使用dict时,如果引用的key不存在,就会抛出KeyError,如果希望key不存在的时候,返回一个默认值,就可以使用defaultdict:
from collections import defaultdict
d: dict = defaultdict(lambda: 'N/A')    # 设置不存在的键,返回N/A
d['key1'] = 'abc'
print(d['key1'])    # 查询存在的键
print(d['key2'])    # 查询不存在的键
>>> 
"""
abc
N/A
"""
4.namedtuple
我们直到tuple可以表示不变的集合,但是我们通常不能直接通过一个集合来看出其表示的含义,比如,我们定义了一个坐标:
p = (1, 2)
但是,我们看到(1,2),很难直到这个tuple是用于表示一个坐标。这时,namedtuple就发挥作用了:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)     # instantiate with positional or keyword arguments
print(p[0] + p[1])      # indexable like the plain tuple (11, 22)
x, y = p                # unpack like a regular tuple
print(x)
print(y)
print(p.x + p.y)        # fields also accessible by name
>>>
"""
33
11
22
33
"""
namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。这样一来,我们使用namedtuple可以很方便地定义一种数据类型。
5.OrderedDict
OrderedDict是一种保存key添加的顺序的dict,Ordereddict的key会按照插入的顺序进行排序,而不是把key本身进行排序。
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(od)
>>>
"""
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
"""
Reference
python标准库说明
 廖雪峰collections