侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

Python基础(18)之collections模块

zze
zze
2019-05-03 / 0 评论 / 0 点赞 / 581 阅读 / 1426 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

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})
0

评论区