美文网首页
Python的收集整理:collections模块

Python的收集整理:collections模块

作者: 多喝酸奶 | 来源:发表于2017-02-14 09:42 被阅读0次

collections模块

collections模块是比较常用的模块,里面有很多实用的类。将最近收集到的用法进行了一些梳理,时不时会更新。

deque双向队列

注意:queue模块中也有deque,用法相同

创建:

from collections import deque
q = deque()
q = deque([1,2,3])
q = deque('abc')

访问,操作(与list类似):

len(q)
q[0]
q[-1]

左右添加,删除:

q = deque('abc')  #['a','b','c']
q.append('d')  #['a','b','c','d']
q.appendleft('e')  #['e','a','b','c','d']
q.pop()  #返回删除元素 ['e','a','b','c']
q.popleft()  #返回删除元素 ['a','b','c']

删除指定元素:

q = deque('abc')  #['a','b','c']
q.remove('b')  #['a','c']

清空:

q.clear()

旋转:

q.rotate(+n)   #向>>>转
q = deque('abcde')  #['a','b','c','d','e']
q.rotate(2)  #['d','e','a','b','c']
q.rotete(-n)  #向<<<转
q = deque('abcde')  #['a','b','c','d','e']
q.rotate(-2)  #['c','d','e','a','b']

创建时可以限制长度

q = deque(maxlen=5)
q = deque([1,2,3],maxlen=4)

当长度超过限制,再从一边添加时,另一边将弹出

q = deque([1,2,3],maxlen=4)  #[1,2,3]
q.append(4)  #[1,2,3,4]
q.append(5)  #[2,3,4,5]
q.appendleft(6)  #[6,2,3,4]

defaultdict 默认字典

访问defaultdict时,如果key不存在,则会返回默认值(通过创建时,调用设置的函数返回)

创建

from collections import defaultdict
def haha():
  return 2
d = defaultdict(haha)  #传入函数名
d['a'] = 1
print(d['a'],d['b'])  #d = {'a':1,'b':2}

#也可以传入已经存在的字典
add = {'c':3, 'd':4}
d = defaultdict(haha,add)
d['a'] = 1
print(d['a'], d['b'], d['c'], d['d'])  #1,2,3,4

小例子

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)  #key不存在时返回一个空list,[]
for k, v in s:
  d[k].append(v)
list(d.items())  #[('blue',[2,4]),('red',[1]),('yellow',[1,3])]
s = 'mississippi'
d = defaultdict(int)  #key不存在时返回0
for k in s:
  d[k] += 1
list(d.items())  #[('i', 4), ('p', 2), ('s', 4), ('m', 1)]

这些函数都可以:list(),str(),int(),tuple(),float(),dict(),set()等
defaultdict和dict.setdefault()方法等价,但速度更快

相关文章

网友评论

      本文标题:Python的收集整理:collections模块

      本文链接:https://www.haomeiwen.com/subject/skmwbttx.html