Python基础(18)之collections模块

Python基础(18)之collections模块

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:

collections 模块中有一些的数据结构类型,使用如下:

namedtuple:带名称的元组

from collections import namedtuple

Point = namedtuple('point', ['x', 'y'])
point1 = Point(1, 2)
point2 = Point(2, 3)
print(point1)  # point(x=1, y=2)
print(point1.x, point1.y)  # 1 2
print(point2)  # point(x=2, y=3)
print(point2.x, point2.y)  # 2 3

deque:双向队列

from collections import deque

dq = deque([1, 2])
dq.append('a')  # 尾部插入  [1,2,'a']
dq.appendleft('b')  # 头部插入 ['b',1,2,'a']
dq.insert(2, 3)  # ['b',1,3,2,'a']
print(dq.pop())  # a 从后面取数据
print(dq.pop())  # 2
print(dq.popleft())  # b 从前面取数据
print(dq)  # deque([1, 3])

OrderedDict:有序字典

# 有序字典
from collections import OrderedDict

od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
for k in od:
    print(k)

# result:
# a
# b
# c

defaultdict:默认字典

from collections import defaultdict

d = defaultdict(lambda: 5)  # 传入callable参数
d['key1'] = 1
print(d['key1'])  # 1
print(d['key'])  # 5 不存在时使用默认值

Counter:计数器

from collections import Counter
c = Counter('abcdeabcdabcaba')
print(c)  # Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://www.zze.xyz/archives/python-base-18.html

Buy me a cup of coffee ☕.