← 返回首页
Python3基础教程(五十六)
发表时间:2022-04-21 18:04:12
collections

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

可以把collections理解为一个容器,里面提供Python标准内建容器 dict , list , set , 和 tuple 的替代选择。

1.常用方法

方法 含义
namedtuple() 创建一个命名元组
deque() 双向列表,类似列表(list)的容器,实现了在两端快速添加(append)和弹出(pop)
defaultdict() 创建一个默认字典
OrderedDict() 创建一个有序字典
Counter() 创建一个计数器

2.命名元组

# -*- coding: utf-8 -*-
# @Time : 2022/4/22 20:43
# @File : collectionsdemo.py
# @Software : PyCharm

import collections

print(dir(collections))

#1. namedtuple() 命名元组
point = collections.namedtuple('Points', ['x', 'y'])
p1 = point(2, 3)
p2 = point(4, 2)

print(p1) # Points(x=2, y=3)
print(p2) # Points(x=4, y=2)

#发现它即属于 point 类型,也属于 tuple 类型
print(isinstance(p1, point)) # True
print(isinstance(p1, tuple)) # True

a= [11, 3]
#使用 _make 赋值
p1= p1._make(a)

print(p1) # Points(x=11, y=3)
#使用 _replace 更改值
p1 = p1._replace(x=5)
print(p1) # Points(x=5, y=3)

运行结果:

['ChainMap', 'Counter', 'OrderedDict', 'UserDict', 'UserList', 'UserString', '_Link', '_OrderedDictItemsView', '_OrderedDictKeysView', '_OrderedDictValuesView', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_chain', '_collections_abc', '_count_elements', '_eq', '_iskeyword', '_itemgetter', '_proxy', '_recursive_repr', '_repeat', '_starmap', '_sys', '_tuplegetter', 'abc', 'defaultdict', 'deque', 'namedtuple']
Points(x=2, y=3)
Points(x=4, y=2)
True
True
Points(x=11, y=3)
Points(x=5, y=3)

3.双向列表

# -*- coding: utf-8 -*-
# @Time : 2022/4/22 20:43
# @File : collectionsdemo.py
# @Software : PyCharm

from collections import deque

q = deque(['a', 'b', 'c'], maxlen=10)
# 从右边添加一个元素
q.append('d')
print(q) 

# 从左边添加一个元素
q.appendleft('x')
print(q) 

# 从左边删除一个元素
print(q.popleft()) # x
print(q) 

# 扩展队列
q.extend(['i', 'j'])
print(q) 

# 查找下标
print(q.index('c')) 

# 移除第一个'd'
q.remove('d')
print(q) 

# 逆序
q.reverse()
print(q) 

# 最大长度
print(q.maxlen) 

运行结果:

deque(['a', 'b', 'c', 'd'], maxlen=10)
deque(['x', 'a', 'b', 'c', 'd'], maxlen=10)
x
deque(['a', 'b', 'c', 'd'], maxlen=10)
deque(['a', 'b', 'c', 'd', 'i', 'j'], maxlen=10)
2
deque(['a', 'b', 'c', 'i', 'j'], maxlen=10)
deque(['j', 'i', 'c', 'b', 'a'], maxlen=10)
10

4.默认值字典

# -*- coding: utf-8 -*-
# @Time : 2022/4/22 20:43
# @File : collectionsdemo.py
# @Software : PyCharm

from collections import defaultdict
dd = defaultdict(lambda: 'not exist')
dd['key1'] = 'abc'
# key1存在
print(dd['key1'])
# key2不存在,返回默认值
print(dd['key2'])

# 使用 list 作为 default_factory ,很容易将序列作为键值对加入字典
d = defaultdict(list)
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

for k, v in s:
    d[k].append(v)

print(d)

# 设置 default_factory 为 int ,可以很好的用于计数
s = 'mississippi'
d = defaultdict(int)
for k in s:
    d[k] += 1

print(d)

运行结果:

abc
not exist
defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})
defaultdict(<class 'int'>, {'m': 1, 'i': 4, 's': 4, 'p': 2})

5.有序字典

OrderedDict的Key会按照插入的顺序排列,不是Key本身排序。但是从Python 3.7 后,dict本身就保证了能够按照插入顺序排序,所以它变得不那么重要了。

# -*- coding: utf-8 -*-
# @Time : 2022/4/22 20:43
# @File : collectionsdemo.py
# @Software : PyCharm

from collections import OrderedDict

dic = dict([('c', 1), ('b', 2), ('a', 3), ('e', 4), ('d', 5)])
# Python 3.7 后dict也是有序的
print(dic)

d = OrderedDict(c=1, b=2, a=3, e=4, d=5)
print(d)
print(d.popitem(last=True))
print(d.popitem(last=False))
print(d)

运行结果:

{'c': 1, 'b': 2, 'a': 3, 'e': 4, 'd': 5}
OrderedDict([('c', 1), ('b', 2), ('a', 3), ('e', 4), ('d', 5)])
('d', 5)
('c', 1)
OrderedDict([('b', 2), ('a', 3), ('e', 4)])

6.计数器

# -*- coding: utf-8 -*-
# @Time : 2022/4/22 20:43
# @File : collectionsdemo.py
# @Software : PyCharm

from collections import Counter

c = Counter()
for i in 'sfsadfsdjklgsdla':
    c[i] +=  1

print(isinstance(c,Counter)) # True
print(isinstance(c,dict)) # True
print(c)

c2 = Counter('asfjslfjsdlfjgkls')
print(c2)

c3 = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
print(c3)

运行结果:

True
True
Counter({'s': 4, 'd': 3, 'f': 2, 'a': 2, 'l': 2, 'j': 1, 'k': 1, 'g': 1})
Counter({'s': 4, 'f': 3, 'j': 3, 'l': 3, 'a': 1, 'd': 1, 'g': 1, 'k': 1})
Counter({'blue': 3, 'red': 2, 'green': 1})

小结:

collections模块提供了一些有用的集合类,可以根据实际需求选用。