Python内建模块 collections

Python内建模块 collections

官方文档:https://docs.python.org/3.6/library/collections.html#module-collections

当遇到了新的类型再更新。

仅记录LeetCode比较常用的语法,别的请参考官方文档。

Counter: dict subclass for counting hashable objects

可以通过一个迭代器来创建Counter,其他的方法类似字典。此外,比起字典,定义了该类型的+-&|

>>> from collections import Counter
>>> c = Counter('gallahad')  # a new counter from an iterable
>>> c
Counter({'g': 1, 'a': 3, 'l': 2, 'h': 1, 'd': 1})
>>> c['c']                   # count of a missing element is zero
0
>>> c['s'] = 0               # counter entry with a zero count
>>> del c['s']               # del actually removes the entry
>>> c.most_common(3)  
[('a', 3), ('l', 2), ('g', 1)]

deque: list-like container with fast appends and pops on either end

Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). deque适合用于队列和栈:deque除了实现list的append()pop()外,还支持appendleft()popleft(),这样就可以非常高效地往头部添加或删除元素。

>>> from collections import deque
>>> q = deque(['a', 'b', 'c']) # 创建deque
>>> q.append('x')     # 右边添加
>>> q.appendleft('y') # 左边添加
>>> q
deque(['y', 'a', 'b', 'c', 'x'])
>>> 
>>> q[0]              # 也可以进行索引
y
>>> 
>>> q.pop()           # 右边弹出
'x'
>>> q
deque(['y', 'a', 'b', 'c'])
>>> q.popleft()       # 左边弹出
'y'
>>> q
deque(['a', 'b', 'c'])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值