04 Feb 2017
假设我们需要记录用户最近5次的操作记录,传统做法是创建一个list,判断list长度,list长度达到5时,每次增加元素,pop出第一个元素,append新的元素。
而collections中的deque函数可以帮我们原生解决这个问题
>>> deque? Docstring: deque([iterable[, maxlen]]) --> deque object Build an ordered collection with optimized access from its endpoints. File: /usr/local/python27/lib/python2.7/collections.py Type: type
>>> from collections import deque >>> q = deque([], 5) >>> q deque([]) >>> q.append(1) >>> q.append(2) >>> q.append(3) >>> q.append(4) >>> q.append(5) >>> q deque([1, 2, 3, 4, 5]) >>> q.append(6) >>> q deque([2, 3, 4, 5, 6])